为什么React类组件中定义的变量无法在state对象中正常使用?
问题原因
你使用类属性语法声明state时,类字段的初始化时机在constructor中super()执行后、this.color = 'blue'赋值代码执行前,因此state初始化阶段this.color还未赋值,自然无法正确传给backgroundColor。
解决方法
以下两种方案都可以解决初始化赋值问题,同时补充点击改色的实现逻辑:
方案1:将state定义移入constructor内部
在constructor里初始化state,能保证读取到已赋值的this.color:
class Squares extends React.Component { constructor() { super(); this.color = 'blue'; // 把state初始化放在constructor内 this.state = { backgroundColor: this.color, width: "50px", height: "50px" }; } // 点击事件处理函数,箭头函数保证this指向组件实例 changeColor = () => { // 示例逻辑:随机生成十六进制颜色,可替换为你自定义的颜色规则 const newColor = '#' + Math.floor(Math.random() * 16777215).toString(16); // 必须调用setState修改state,不能直接赋值修改 this.setState({ backgroundColor: newColor }) } render () { return ( <div> <div style={this.state}>Hello</div> <button onClick={this.changeColor}>Change Square Color</button> <p>{this.state.backgroundColor}</p> </div> ); } }
方案2:将color也定义为类属性
不用把this.color放在constructor里赋值,直接声明为类属性,和state的初始化时机一致:
class Squares extends React.Component { // 类属性声明color,和state初始化时机同步 color = 'blue'; state = { backgroundColor: this.color, width: "50px", height: "50px" }; changeColor = () => { const newColor = '#' + Math.floor(Math.random() * 16777215).toString(16); this.setState({ backgroundColor: newColor }) } render () { return ( <div> <div style={this.state}>Hello</div> <button onClick={this.changeColor}>Change Square Color</button> <p>{this.state.backgroundColor}</p> </div> ); } }
注意事项
- React的state是不可变数据,不能直接修改
this.state.backgroundColor的值,必须调用this.setState方法更新,更新后组件会自动重新渲染刷新视图。 - 类组件的事件处理函数用箭头函数声明,可以避免this指向丢失的问题,不用额外在constructor里做bind绑定。
内容的提问来源于stack exchange,提问作者Devin
相关产品推荐
相关产品推荐

