使用 React 随机更改背景颜色的函数

Function to Randomly Change Background Color with React

我正在尝试定义一个函数,当用户单击按钮时更改主页的背景颜色。

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      quotes: [], 
      selectedQuoteIndex: null,
      background: 'white'
    }   
    this.changeBackground = this.changeBackground.bind(this);
  }

  changeBackground() {
    return random(backgroundColor);
  }        

  render() {
    return (
      <button onClick={this.changeBackground}/>
    )   
  }
}

我不知道把return背景颜色放在哪里。

首先,changeBackground 不应该 return 任何东西。相反,它应该 setState 和一个新的随机生成的 backgruond,这是一个代表 RGB 颜色的十六进制字符串。

  changeBackground() {
    let background = "#" + ((1<<24)*Math.random() | 0).toString(16);
    this.setState({background});
  }

然后,您需要使用 state.background 设置背景样式。这里我 return div 组件作为背景填充整个视口。

  render() {
    return (
      <div style={{
        width: '100vw',
        height: '100vh',
        backgroundColor: this.state.background
      }}> 
        <button onClick={this.changeBackground}/>
      </div>
    )   
  }
}