gpt4 book ai didi

javascript - 按钮单击时更改颜色

转载 作者:行者123 更新时间:2023-12-01 23:27:07 26 4
gpt4 key购买 nike

我目前正在使用 react-native。我的目标是让按钮的颜色在每次被点击时变成随机颜色。

import React, { Component } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';

export default class App extends Component {
constructor() {
super();
this.state = {
counter: 0,
buttonColor: 'blue',
};
}
componentDidMount() {
setInterval(this.incrimentCounter, 100000000000);
}
//incrimentCounter = () => {
//this.setState({ counter: this.state.counter + 1 });
// };
componentDidUpdate() {
console.log('Counter value has changed');
}
changeColor = () => {
var letters = '0123456789ABCDE'
var color = "#"

};
render() {
return (
<View style={{ flex: 1 }}>
<Text style={{ marginTop: 50, marginLeft: 170 }}>
{this.state.counter}
</Text>
<Button
title="Click"
color={this.state.buttonColor}
onPress={this.changeColour}></Button>
</View>
);
}
}

这里有小吃供引用。 https://snack.expo.io/@therealsneh/df3efe我在第 21 行有一个名为“changeColor”的箭头函数。我已经定义了 2 个变量、字母和 hexaDecimalHash。使用这两个变量,我将能够创建一个随机的十六进制数,例如 #4934eb。使用这种随机的十六进制颜色,按钮将看起来像那样。谢谢!

最佳答案

这样试试。我认为它对您有用。

import React, { Component } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';

export default class App extends Component {
constructor() {
super();
this.state = {
counter: 0,
buttonColor: 'blue',
};
}
componentDidMount() {
setInterval(this.incrimentCounter, 100000000000);
}
incrimentCounter = () => {
this.setState({ counter: this.state.counter + 1 });
};
componentDidUpdate() {
console.log('Counter value has changed');
}
changeColor = () => {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
if(color==="#FFFFFF") return;
this.setState({
buttonColor:color
})

};
render() {
return (
<View style={{ flex: 1 }}>
<Text style={{ marginTop: 50, marginLeft: 170 }}>
{this.state.counter}
</Text>
<Button
title="Click"
style={{color:this.state.buttonColor}}
onPress={this.changeColor}></Button>
</View>
);
}
}

好吧,它在这里工作 https://snack.expo.io/AfmXSZ9R1

关于javascript - 按钮单击时更改颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67051730/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com