我有一个 ListView
组件,其中我需要根据 onPress 事件独立更改每行的背景颜色。
<View style = {[styles.checkBox, {backgroundColor: this.state.button[rowID]? '#62C6C6':'transparent'}]}/>
因为我不知道会渲染多少行,但最多有4行,所以我声明了一个数组状态button
为[false, false, false, false]
并根据行更改元素值。例如,当我按下第一行时,rowID
为0,我会将button
的状态设置为[true, false, false, false]
。在此方法中,button
的状态发生更改,但 UI 不会重新呈现背景颜色。
我认为这里的逻辑是正确的(是吗?),有什么方法可以得到预期的结果或者有更聪明的方法来实现这一点
最佳答案
建议创建您自己的组件以在每行内呈现,并且仅在单击时更改该组件的背景。这意味着您不需要保留每个组件本身的状态数组。
这将是您的组件:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
backgroundColor:'transparent'
}
}
render() {
return (
<View style={{ backgroundColor: this.state.backgroundColor}}>
<TouchableOpacity onPress={this.changeColor.bind(this)}>
<Text>This is my Component</Text>
</TouchableOpacity>
</View>
);
}
changeColor(){
this.setState({
backgroundColor:'#62C6C6'
});
}
}
然后在 renderRow 中你可以调用你的组件:
renderRow(rowData){
return(
<View>
<MyComponent/>
</View>
)
}
关于javascript - 状态数组中的更改元素不会触发 UI 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40686956/