this2.props не определено с помощью createTopTabBarNavigator - PullRequest
0 голосов
/ 09 октября 2019

Внутри навигатора панели вкладок, я использую библиотеку карусели и onPress элемента, который я хочу перейти к другому компоненту. Моя первая вкладка имеет flatList, я могу получить доступ к this.props.navigation.navigate,

, но на второй вкладке, где я использую библиотеку карусели внутри _renderItem,

Яне может получить доступ this.props.navigation.navigate. Это всегда выдает ошибку this2.props .....

(я использую реагирующую навигацию версии 4.X)

export default class ListTab extends Component {
    constructor(props) {
        super(props);
        console.info(this.props)
        this.state = {
            isLoading: true,
            isConnected: false,
            dataSource: []
        }
    }

    componentDidMount = async () => {
        await NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectionChange)
        AsyncStorage.getItem(USER_NAME, (error, result) => {
            if(result) {
                let data = {
                    method: 'POST',
                    credentials: 'same-origin',
                    mode: 'same-origin',
                    body: JSON.stringify({
                        'data': result,
                    }),
                    headers:{
                        'Accept':   'application/json',
                         'Content-Type': 'application/json',
                    }
                }
                if(this.state.isConnected) {
                    fetch(BaseUrl + 'my/endpoint/url', data)
                    .then((response) => response.json())
                    .then((responseJson)=> {
                        this.setState({
                            isLoading: false,
                            dataSource: responseJson.data
                        })
                    })
                    .catch((error) => {
                        console.log(error)
                    })
                } else  {
                    alert(NO_INTERNET)
                }  
            } else {
                console.log(error)
            }
        })
    }

    handleConnectionChange = async (isConnected) => {
        await this.setState({isConnected}); 
    }

    _renderItem({item,index}) {
        var allcat = [];
        for(let i = 0; i < item.data.length; i++){
          allcat.push(
            <TouchableOpacity onPress={() => {this.props.navigation.naviate('FlavoursDetails')}}>
                <Text style={styles.SectionListItemStyle}>{item.data[i].itemname}</Text>
            </TouchableOpacity>
          )
        }
        return (     
          <ScrollView style={{
          flex:1, width:'100%',
          shadowRadius: 4.65,elevation: 10,  borderWidth:1, borderColor:'#ccc', margin:0, padding:0, borderRadius:10,marginTop:30, backgroundColor:'#fff', }}>
           <Text style={styles.SectionHeaderStyle}>{item.title}</Text>
           {allcat}
            </ScrollView>
        )
     }
    render() {
        if(this.state.isLoading){
            return(
              <View style={{flex: 1, flexDirection:"column", alignItems:"center",alignSelf:"center", padding: 20}}>
                <ActivityIndicator/>
              </View>
            )
        }
        return (
            <ImageBackground style={{flex:1}}
            source={require('../../assets/app_background.jpg')}>
                <SafeAreaView style={{flex:1, alignItems:'center'}}>
                    <StatusBar
                        barStyle="light-content"
                        backgroundColor= {appColor}/>
                        <Carousel
                            ref={'carousel'}
                            data={this.state.dataSource}
                            sliderWidth={1000}
                            itemWidth={300}
                            renderItem={this._renderItem}/>
                </SafeAreaView>
            </ImageBackground>         
        );
    }
}

const styles = StyleSheet.create({
    SectionHeaderStyle: {
        textAlign: 'left', 
        alignSelf: 'center',
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 3,
        },
        shadowOpacity: 0.29,
        shadowRadius: 4.65,
        elevation: 7,
        fontWeight:"bold",
        width:'100%', 
        backgroundColor : '#fff',
        borderRadius:10,
        color:'#001E41', 
        padding: 20,
        fontSize: 18, 
        marginTop:0,
        marginBottom:10,
    },
    SectionListItemStyle:{
      fontSize : 15,
      paddingLeft: 0, 
      paddingTop:10,
      paddingBottom:10,
      width:'85%',
      color: appColor,
      fontWeight:"normal",
      backgroundColor : '#fff',
      borderBottomWidth: 1,
      alignSelf: "center",
      borderColor: '#DDE0E5',
      textAlign: 'left',
      alignItems: 'center',
    }
});

1 Ответ

0 голосов
/ 09 октября 2019
    _renderItem({item,index}) {
    var allcat = [];
    for(let i = 0; i < item.data.length; i++){
      allcat.push(
        <TouchableOpacity onPress={() => {this.props.navigation.naviate('FlavoursDetails')}}>
            <Text style={styles.SectionListItemStyle}>{item.data[i].itemname}</Text>
        </TouchableOpacity>
      )
    }

Замените вышеуказанный код следующим:

_renderItem({item,index}) {
    var allcat = [];
    for(let i = 0; i < item.data.length; i++){
      allcat.push(
        <TouchableOpacity onPress={() => {this.props.navigation.navigate('FlavoursDetails')}}>
            <Text style={styles.SectionListItemStyle}>{item.data[i].itemname}</Text>
        </TouchableOpacity>
      )
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...