【发布时间】:2018-01-24 19:18:41
【问题描述】:
所以我的代码是:
export default class MyClass extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{id: 101, name:"One", thevalue:11},
{id: 102, name:"Two", thevalue:22},
{id: 103, name:"three", thevalue:33}
]
}
}
handleOnPress() {
<< HOW DO I CODE THIS ?? >>
I want to increase the number count in thevalue of the pressed item
}
render() {
return(
<FlatList
data = {this.state.data}
renderItem = {
({item}) =>
<TouchableOpacity onPress={this.handleOnPress} >
<Text> {item.name} + {item.thevalue} </Text>
</TouchableOpacity>
}
/>
)
}
}
我希望能够增加仅单击项目的thevalue 的计数。所以我应该做一个setState 对吗?但是我怎么知道我需要在哪个项目上运行它?我需要将点击的项目的id 传递给函数吗?如果是,我该怎么做?
非常感谢。
更新1:
handleOnPress(id) {
this.setState({
thevalue: this.state.thevalue+1
});
}
【问题讨论】:
-
您可以在
onPress中提供item吗?例如:{this.handleOnPress(item)}或类似? -
@JeffHuijsmans 你不能这样称呼它,否则将在渲染每个项目时调用 handleOnPress。你需要按照我的回答做点什么:)
-
@MattDerrick 很好,谢谢!我在想另一个框架:)
-
为什么不创建一个项目组件并在其中按下处理?在 MyClass 中只渲染列表。
标签: javascript reactjs react-native