按钮在点击时改变颜色

时间:2021-04-12 01:48:09

标签: javascript reactjs react-native button expo

我目前正在使用 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。使用这种随机的十六进制颜色,按钮看起来像这样。谢谢!

2 个答案:

答案 0 :(得分:3)

试试这个。 我认为它可以为您工作。

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

答案 1 :(得分:3)

生成随机数并将其push转化为color,然后附加Hash + color

Demo

changeColor = () => {
  var letters = '0123456789ABCDE'.split("");
  var hexaDecimalHash = "#";
  const color = [];
  while (color.length !== 6) {
    color.push(letters[Math.floor(Math.random() * letters.length + 1)])
  }
  this.setState({
    buttonColor: `${hexaDecimalHash}${color.join("")}`
  })
};