我有一个<TouchableWithoutFeedback>
环绕的视图,我想在单击时onPressIn
更改该视图的颜色,但是所有视图的颜色都会改变,我的意思是映射视图,请问如何使onPressIn更改仅特定视图的样式,并非全部
const herbs = this.state.record.map(herb => (
<TTouchableWithoutFeedback
onPressIn={() => this.setState({ pressed: !this.state.pressed })}
key={herb.id}
>
<View style={this.state.pressed ? BackStyles.herbBox : BackStyles.herb_box}>
<Image
style={BackStyles.image}
source={{ uri: `${herb.name.replace(/ /g, "")}` }}
/>
<View style={{ flexDirection: "column" }}>
<Text style={BackStyles.header}>{herb.name}</Text>
<Text style={BackStyles.sub}>{herb.bot}</Text>
</View>
</View>
</TTouchableWithoutFeedback>
));
const BackStyles = StyleSheet.create({
herb_box: {
backgroundColor: "#fff",
borderRadius: 7,
marginTop: 10,
marginBottom: 10,
flexDirection: "row",
width: "95%",
alignSelf: "center"
// height: '2%'
// justifyContent: 'center',
},
herbBox: {
backgroundColor: "#28B564",
borderRadius: 7,
marginTop: 10,
marginBottom: 10,
flexDirection: "row",
width: "95%",
alignSelf: "center"
}
});
您必须跟踪TTouchableWithoutFeedback
通过创建的每个组件的布尔状态map
。
与其pressed
成为布尔值,不如使其成为对象以跟踪每个组件。
与此类似的东西。
class App extends Component {
state = {
pressed: {}
};
handlePressedIn = i => {
this.setState(prevState => {
const pressed = { ...prevState.pressed };
pressed[i] = !pressed[i];
return { pressed };
});
};
render() {
const herbs = this.state.record.map((herb, i) => (
<TTouchableWithoutFeedback
onPressIn={() => this.handlePressedIn(i)}
key={herb.id}
>
<View
index={i}
style={
this.state.pressed[i] === i && this.state.pressed
? BackStyles.herbBox
: BackStyles.herb_box
}
>
<Image
style={BackStyles.image}
source={{ uri: `${herb.name.replace(/ /g, "")}` }}
/>
<View style={{ flexDirection: "column" }}>
<Text style={BackStyles.header}>{herb.name}</Text>
<Text style={BackStyles.sub}>{herb.bot}</Text>
</View>
</View>
</TTouchableWithoutFeedback>
));
return <div>{herbs}</div>;
}
}
这是一个补充说明,用于解释代码的工作原理。@Aravind S
提问
您能否在回答中澄清我的疑问?被按下的是被按下的对象:{}并在handlePressed中正在被按下[i] =!pressed [i]; 我在哪里是视图的索引...它的数组然后...对吗?您是否返回对象数组?那么它如何运作?
pressed[i]
最初undefined
是用户首次点击时。但是!undefined
返回true,因此的初始值为pressed[i]
true。
pressed: {}
被初始化为仅存储所需数据的对象。
如果将其初始化为array pressed: []
,则会浪费带有undefined
值的空间。
基本上return { clicked }
返回以位置(索引)为键的对象/字典。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句