javascript - 如何在多个状态更改中的每一个上重新渲染组件?
问题描述
我还在学习 JS/React,所以很可能我做错了。欢迎任何批评。
我有一个画布,上面有一幅画。我想在按下按钮时多次更改绘图的颜色。要清楚:我想单击按钮多次更改绘图的颜色。
我已经尝试过几种不同的方式,但它们主要是两种方式的变体:
当按钮被按下时,它会调用将多次更改状态的方法,但 React 只需要渲染我设置的最后一个状态。(这是有道理的)
使用
setTimeout
for eachsetState
,但它似乎破坏了方法,并且渲染永远不会改变。
这是一个示例代码:
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;
我做错了什么,如何通过反应实现多种颜色变化?
解决方案
没有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>
推荐阅读
- php - 如何获取数组的所有唯一组合,包括空格(项目顺序不相关)
- android - 如何在 Android 应用程序中验证 SSL 证书的有效性
- javascript - Angular:如何在单元测试夹具中获取 @ViewChild 引用或模拟它
- java - @RunWith(MockitoJUnitRunner.class) 和 @RunWith(SpringJUnit4ClassRunner.class) 有什么区别?何时适当使用?
- python - 如何在 Panda DataFrame 中添加不完整的行?
- javascript - Shaka Player:忽略空的 AdaptationSet
- wpf - 有没有办法将日期选择器文本框绑定到 resx 文件和密钥,并且仍然保持作为日期选择器的功能?
- apache - Apache 上的“状态”参数是什么?
- javascript - 将内容下移到固定位置标题后面
- php - 如何过滤数组php