将flatlist组件键作为参数传递

问题描述 投票:-1回答:1
import {View,Text,StyleSheet,FlatList,TouchableOpacity,Dimensions,AsyncStorage} from 'react-native';
import {Font, LinearGradient} from "expo";
const data = [
  { key: 'Addition'  }, { key: 'B' }, { key: 'C'  },{ key: 'D'},
  { key: 'E'  },{ key: 'F'  }
];

const numColumns = 1;
export default class GScreen extends React.Component {
  renderItem = ({ item, index }) => {
    return (
      <LinearGradient
          colors={['#2c81af','#92ede8']}
          style={styles.contcontainer}
          >
          <TouchableOpacity
          onPress={(item) =>{this.props.navigation.navigate('AScreen', {content : 'Addition' });}}>
            <Text style={styles.title}>{item.key}</Text>
          </TouchableOpacity>
      </LinearGradient>
    );
  };

  render() {
    return (
      <FlatList
        data={data}
        style={styles.container}
        renderItem={this.renderItem}
        numColumns={numColumns}
      />
    );
  };
}

对于thiis flatlist的每个组件,我想在导航到AScreen而不是'Addition'(或任何单个值)时将{item.key}作为参数传递。我如何实现这一目标?

react-native react-navigation react-native-flatlist
1个回答
1
投票

问题不在于对象的传递,而在于如何在onPress中构建TouchableOpacity函数

目前这是你拥有的:

<TouchableOpacity
  onPress={(item) =>{this.props.navigation.navigate('AScreen', {content : 'Addition' });}}>
  <Text style={styles.title}>{item.key}</Text>
</TouchableOpacity>

请注意,在你的onPress函数中你有(item) => {...}函数中的单词item将覆盖你对item的值。这就是为什么你得到undefined。您需要做的就是从函数调用中删除单词item

如果您将代码更改为以下内容,则应按预期传递该值

<TouchableOpacity
  onPress={() =>{this.props.navigation.navigate('AScreen', {content : item.key });}}>
  <Text style={styles.title}>{item.key}</Text>
</TouchableOpacity>

请注意,onPress现在是() => {...}。这应该会阻止item的值被覆盖

© www.soinside.com 2019 - 2024. All rights reserved.