【发布时间】:2021-07-28 07:58:05
【问题描述】:
所以这里我有 3 个 TouchableOpacities,每次按下时 backgroundColor 都会改变它的自身并且工作正常,所以我尝试在我的 changeColor() 函数中添加一个 setState,它返回每个按下的 TouchableOpacity 的大小(M、L 或 XL) 这是我的代码:
constructor(props) {
super(props)
colorId: 0,
size:""
};
}
changeColor = (id) => {
this.setState({ colorId: id });
if (id == 1) {
this.setState({ size: 'M' })
}
else if (id == 2) {
this.setState({ size: 'XL' })
}
else {
this.setState({ size: 'L' })
}
console.log("Button id:", id ,"size :", this.state.size)
}
render() {
return (
<TouchableOpacity style={this.state.colorId === 2 ? styles.button_XL_Colored : styles.button_XL} onPress={() => this.changeColor(2)} ><Text style={{ color: '#000000', alignSelf: 'center', marginTop: normalize(12), fontSize: normalize(20) }}>XL</Text></TouchableOpacity>
<TouchableOpacity style={this.state.colorId === 3 ? styles.button_L_Colored : styles.button_L} onPress={() => this.changeColor(3)}><Text style={{ color: '#000000', alignSelf: 'center', marginTop: normalize(12), fontSize: normalize(20) }}>L</Text></TouchableOpacity>
<TouchableOpacity style={this.state.colorId === 1 ? styles.button_M_Colored : styles.button_M} onPress={() => this.changeColor(1)} ><Text style={{ color: '#000000', alignSelf: 'center', marginTop: normalize(12), fontSize: normalize(20) }}>M</Text></TouchableOpacity>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5F5F8',
},
button_M: {
backgroundColor: '#FFFDFD',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
marginLeft: 0,
marginTop: normalize(-10)
},
button_L: {
backgroundColor: '#FFFDFD',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
marginLeft: normalize(140),
},
button_XL: {
backgroundColor: '#FFFDFD',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
},
button_M_Colored: {
backgroundColor: '#D05A0B',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
marginLeft: 0,
marginTop: normalize(-10)
},
button_XL_Colored: {
backgroundColor: '#D05A0B',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
},
button_L_Colored: {
backgroundColor: '#D05A0B',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
marginLeft: normalize(140),
},
当我按下带有 M 字母的 TouchableOpacity 时,它应该返回 size="M"
只有按两次才有效:
其他 touchableOpacities 的情况相同:
有什么解决办法吗?
【问题讨论】:
-
setState 异步更新状态。如果您想像 reactjs.org/docs/react-component.html#setstate 那样记录,请使用回调参数
标签: javascript node.js reactjs react-native