【问题标题】:React Native variables between JavaScript classes在 JavaScript 类之间反应原生变量
【发布时间】:2017-12-03 21:14:48
【问题描述】:

我正在尝试使用 react-navigation 设置导航操作,但我遇到了麻烦,因为我使用的是 FlatList 和 Pure Component 来呈现列表中的项目。该列表呈现正常,但是当我尝试将 onPress 函数添加到 TouchableHighlight 时,我无法调用正常的导航函数,因为它不知道变量导航的含义。如果可能的话,我想为纯组件保留单独的文件,而不是将其移动到其他类中。

纯组件:

export default class Lot extends React.PureComponent {

    render() {
        return (
            <TouchableHighlight
                onPress={() => navigate('LotView')}
            >
                <View style={{ flex: 1, height: 150, alignItems: 'center', justifyContent: 'center' }}>
                    <View>
                        {this.props.active && (<Image source={images[this.props.index]} style={[styles.images]} />)}
                    </View>

                 </View>

            </TouchableHighlight>
        );
    }
}

以下内容在我的 App.js 类中。

平面列表

<FlatList
    data={this.state.lots}
    renderItem={({ item }) => <Lot {...item} />}
/>

导航屏幕

export const MyApp = StackNavigator({
    Home: { screen: HomeScreen },
    LotView: { screen: LotView },
});

【问题讨论】:

    标签: javascript react-native react-native-flatlist


    【解决方案1】:

    Lot 应该是虚拟组件(不应有任何外部访问权限)

    export default class Lot extends React.PureComponent {
    
        render() {
            return (
                <TouchableHighlight
                    onPress={this.props.onPress} // <== CHANGED
                >
                    <View style={{ flex: 1, height: 150, alignItems: 'center', justifyContent: 'center' }}>
                        <View>
                            {this.props.active && (<Image source={images[this.props.index]} style={[styles.images]} />)}
                        </View>
    
                     </View>
    
                </TouchableHighlight>
            );
        }
    }
    

    主屏幕

    <FlatList
        data={this.state.lots}
        renderItem={({ item }) => <Lot {...item} onPress={() => this.props.navigate('LotView')} />} //<== CHANGED
    />
    

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多