现在我有一个学校项目在手机上构建应用程序。我们正在使用React Native和Java。我想在应用程序中创建一个按钮,当按下该按钮时会变为随机颜色。但是,这不起作用。
以下是我的代码片段:
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {color: "#000000"}
}
render() {
let color = this.state.color;
return (
...
<View>
<Button
onPress = {changecolor}
title = "This button changes color when pressed"
color = {color}/>
</View>
...
numbers = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
this.random = this.numbers[Math.floor(Math.random() * this.numbers.length)];
function changecolor() {
this.replaceState({color: String("#"+random+random+random+random+random+random)});
}
在按钮仅变成灰色阴影而不是任何颜色之前,我还有一个问题。有什么帮助吗?
编辑:我应该提到我以前使用过this.setState,并且结果相同
答案 0 :(得分:0)
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {color: "#000000"}
}
render() {
let color = this.state.color;
return (
<View>
<Button
onPress = {this.changecolor}
title = "This button changes color when pressed"
color = {color}/>
</View>
numbers = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
this.random = this.numbers[Math.floor(Math.random() * this.numbers.length)];
changecolor() {
this.replaceState({color: String("#"+random+random+random+random+random+random)});
}
}
答案 1 :(得分:0)
changecolor
甚至是HomeScreen
类的成员吗?看起来好像不是这样,考虑到它是用function
声明的,并且没有解析错误在向您尖叫。使其成为一种方法,更好的是,使它成为箭头函数:
changecolor = () => {
this.replaceState({color: String("#"+random+random+random+random+random+random)});
}