【问题标题】:Change screen FlatList onPress换屏 FlatList onPress
【发布时间】:2017-08-29 01:53:05
【问题描述】:

我有两个屏幕。 第一个屏幕是 HomeScreen,第二个屏幕是 ProfileScreen。 我在 HomeScreen 上使用了 FlatList,我想将导航推送到另一个屏幕。但是当我使用该代码时,我看到了错误消息:“无法读取未定义的属性'导航'”

这样的代码

class ProfileScreen extends Component {

    static navigationOptions = {
      title: 'Profile',
    };

    render() {
        const { navigate } = props.navigation;

        return <Text>Hello, I am profile!</Text>;
    }
 }




class HomeScreen extends Component {

    static navigationOptions = {
        title: 'Home',
    };


    constructor(props) {
        super(props);

        this.state = {
            data: [],

        };


    }

    getScreen() {
        this.props.navigation.navigate('Profile')
    }

    render() {

        return (
            <View>
                <FlatList
                    data={this.state.data}
                    renderItem={({ item }) => (
                        <TouchableHighlight underlayColor= 'transparent' onPress= {this.getScreen}>
                            <View style= {{width: 300, height: 'auto'}} >
                            <Text> {item.title} </Text>
                                <View style= {{width: 300, height: 1, backgroundColor: 'red', marginBottom: 30, marginTop: 15}} /> 
                            </View>
                        </TouchableHighlight>
                    )}
                />
            </View>
        );
    }
}



const AppNavigator = StackNavigator({
    Home: { screen: HomeScreen },
    Profile: { screen: ProfileScreen }
});

【问题讨论】:

  • 尝试使用 this.props.navigation 并在最后添加这一行 export default AppNavigator
  • 我不明白,你能解释一下吗?
  • 更改 const {navigation} = this.props.navigation
  • 我也遇到同样的问题,你解决了吗?

标签: react-native


【解决方案1】:

您在实现中丢失了this 的上下文。用函数调用修复它:

renderItem={({ item }) => (
  <TouchableHighlight underlayColor='transparent' onPress={() => this.getScreen()}>
  ...
  </TouchableHighlight>
)}

另外,还可以使用pattern:

const { navigate } = this.props.navigation;

navigate('Profile');

【讨论】:

  • 可能不是这个原因,我也遇到同样的问题,不行
【解决方案2】:

在构造函数中将 this 绑定到你的 getScreen 方法。

只需在构造函数中添加以下行。

this.getScreen = this.getScreen.bind(this);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多