0

我有一个屏幕显示列表中的一些项目。我的项目是一个名为 CardItem 的组件,它有几个按钮。我像上面一样实现了但是当我运行我的项目时,组件将我想要的数据传递给初始化状态的父方法,但是当用户单击该按钮时我需要它。

家长:

addItemQuantity = (id) => {
  console.log('ADD item quantity with id: ', id);
};

render() {  
   return (
      <CardItem
         data={item}
         index={idx}
         key={item._id}
         addItemQuantityPress={this.addItemQuantity}
      />
   )

}

孩子:

handleAddItemQuantity = (id) => {
  console.log('child component method');
  this.props.addItemQuantityPress(id);
}

render() {
    return (
        <View style={styles.cardItemOperation} >
            <TouchableHighlight
                underlayColor="#ffffff"
                onPress={this.handleAddItemQuantity(this.props.data._id)}
                style={styles.icon} >
            <Image
                style={styles.icon}
                resizeMode="contain"
                source={require('./images/icon-add.png')} />
            </TouchableHighlight>
       </View>
    )
}

运行项目时的输出:

child component method
ADD item quantity with id: 5a2660924713cf6c8d088424
child component method
ADD item quantity with id: 5a1a58cacd0b8a0febce9fd7
child component method
ADD item quantity with id: 5a1a5856cd0b8a0febce9fd5
child component method
ADD item quantity with id: 5a4c8e9d2ebcf507323e7b73
child component method
ADD item quantity with id: 5a1a5862cd0b8a0febce9fd6

4

1 回答 1

1

正如你在那里写的,

this.handleAddItemQuantity(this.props.data._id)

将在渲染时立即执行。将其更改为:

onPress={() => {this.handleAddItemQuantity(this.props.data._id)}}

这应该够了吧

于 2018-01-21T12:06:27.967 回答