[英]Why doesn't react update the style in the setState?
为什么不反应更新 setState 中的样式? 文本的颜色不会通过 setState 函数更新为绿色,而是保持蓝色。
class Practice extends Component {
state = {
count: 0,
color: "blue"
}
style = {
color: this.state.color
}
handleIncrement = () => {
this.setState({ count: this.state.count});
this.setState({ color: "green"});
}
render() {
return(
<div>
<h1 style={this.style}>
The color in this state is {this.state.color}.
The number in count is {this.state.count}.
<button
onClick={this.handleIncrement}
>
Increment
</button>
</h1>
</div>
);
}
}
有关组件应如何呈现的信息应仅从状态流出 - 这将允许您调用setState
来更改组件的呈现方式。 将.style
属性放在组件实例本身上是行不通的 - 而是将其放入状态。
与其在 state 的不同部分复制颜色,不如把它放在一个地方,在 state 的style
对象中。
不是 100% 确定,但您也可能想要
this.setState({ count: this.state.count});
成为
this.setState({ count: this.state.count + 1 });
class Practice extends React.Component { state = { count: 0, style: { color: 'blue', } } handleIncrement = () => { this.setState({ count: this.state.count + 1 }); this.setState({ style: { ...this.state.style, color: "green" }}); } render() { return( <div> <h1 style={this.state.style}> The color in this state is {this.state.style.color}. The number in count is {this.state.count}. <button onClick={this.handleIncrement} > Increment </button> </h1> </div> ); } } ReactDOM.render(<Practice />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>
虽然其他答案很好地解释了为什么您的代码在 React 状态方面不起作用,但我注意到一件事可能是另一个混淆点。
当您像这样为style
属性分配值时:
style = {
color: this.state.color
}
您可能认为您正在为style.color
指定this.state.color
指向的字符串的“引用”。 实际发生的是您正在分配值"blue"
,因为字符串是 JS 中的原始类型。 所以在你这样做之后,你的style
对象真的只是
{
color: "blue"
}
因此,即使您以某种方式更改了this.state.color
的值,这从根本上也不会导致更新this.style.color
的值。
当且仅当您在this.state
中this.state
state
,react app 中的state
才会使用setState
更新,如果您使用的是constructor
或state
属性而没有constructor
。
现场演示
您应该将状态创建为:
state = {
count: 0,
style: {
color: "blue"
}
};
并将状态更新为:
handleIncrement = () => {
this.setState((oldState) => {
return {
count: oldState.count + 1,
style: {
...oldState.style,
color: "green"
}
};
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.