首页 > 解决方案 > 如何在多个状态更改中的每一个上重新渲染组件?

问题描述

我还在学习 JS/React,所以很可能我做错了。欢迎任何批评。

我有一个画布,上面有一幅画。我想在按下按钮时多次更改绘图的颜色。要清楚:我想单击按钮多次更改绘图的颜色。

我已经尝试过几种不同的方式,但它们主要是两种方式的变体:

这是一个示例代码:

import React from 'react';

class App extends React.Component {
 constructor(props) {
      super(props);
      this.state = {
        color: "#000000",
      }
      this.changeColors = this.changeColors.bind(this);
  }
  
  changeColors() {
    let colors = ["#000000", "#0000FF", "#FF0000", "#00FF00"];
    for (let nextColor in colors) {
      console.log(`Color now ${colors[nextColor]}`);
      // This seems to break it
      //setTimeout(function(){ this.setState({color: colors[nextColor]}); }, 3000);

      // This only renders last state
      this.setState({color: colors[nextColor]});
    }
  }

  render() {
    return (
      <div className="App">
        <h1>Change Colors</h1>
        <MyButton changeColor={this.changeColors}/>
        <MyCanvas color={this.state}/>
      </div>
    );
  }
}

class MyButton extends React.Component {
  render() {
    return (
      <button 
        type="button" 
        className="btn btn-secondary" 
        onClick={() => this.props.changeColor()}>
        Color
      </button>
    );
  }
}

class MyCanvas extends React.Component {
  componentDidMount() {
      this.drawOnCanvas(this.props.color)
  }
  
  componentDidUpdate() {
      this.drawOnCanvas(this.props.color)
  }
  
  drawOnCanvas(color) {
    const ctx = this.refs.canvas.getContext('2d');
    ctx.clearRect(0, 0, 300, 300) 
    ctx.fillStyle=color.color;
    ctx.fillRect(10, 10, 100, 100);
  }
  
  render() {
    return (
      <canvas id="canvas" ref="canvas" width={300} height={300}/>
    );
  }
}

export default App;

我做错了什么,如何通过反应实现多种颜色变化?

标签: javascriptreactjssetstate

解决方案


没有setTimeout所有的渲染将基本上合并为一个,这就是 React 的工作原理。但是,您可以尝试setTimeout使用动态超时。

class App extends React.Component {
 constructor(props) {
      super(props);
      this.state = {
        color: "#000000",
      }
  }
  
  changeColors = () => {
    let colors = ["#000000", "#0000FF", "#FF0000", "#00FF00"];
    colors.forEach((color, i) => {
      setTimeout(() => {
          this.setState({ color });
      }, 500 * i);
    });
  }

  render() {
    return (
      <div className="App" style={{ color: this.state.color }}>
        <h1>Change Colors</h1>
        <button onClick={this.changeColors}>change</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>


推荐阅读