我想让按钮在按下时改变颜色。我尝试查看其他类似的主题,但找不到解决方案。代码呈现并且初始按钮颜色为红色,但是当我按下它时,没有任何反应。
export default class someProgram extends Component {
render() {
var buttonColor = "red";
function changeButtonColor(){
if(this.buttonColor === "red"){
this.buttonColor = "green";
}
else{
this.buttonColor = "red";
}
}
return (
<View style={styles.container}>
<Button
title="Press me!"
color={buttonColor}
onPress={() => {changeButtonColor(buttonColor)}}
/>
</View>
);
}
}
最佳答案
您应该跟踪组件状态中的颜色。另一方面,请确保了解关键字 this 的真正含义。做一个console.log(this)
并亲自看看。
无论如何,你可以
(1)在构造函数中设置初始状态;
(2) 使用 this.state.someProp
从状态访问值
然后 (3) 稍后使用 this.setState({ someProp: someValue })
调整状态.
1) 初始状态
constructor(props) {
super(props);
this.state = {
buttonColor: 'red'; // default button color goes here
};
}
2) 访问状态& 3)设置新状态
onButtonPress = () => {
this.setState({ buttonColor: 'someNewColor' });
}
render() {
// ...
return (
{/* ... */}
<Button
color={this.state.buttonColor}
onPress={onButtonPress}
/>
)
请注意,为了关注当前的问题,省略了代码的某些部分。
关于android - 使用 React Native 上的 onPress 更改按钮颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42165428/