为什么这个react按钮在按下时不会更改div文本的颜色



我的问题是,为什么这个按钮在按下时没有将div文本颜色更改为绿色?

这是代码,我希望它能对你有用,帮助我解决这个疑问:

import React from 'react';
import hola from './hola.css'
class Child extends React.Component {
constructor(props) {
super(props);
this.state = { color: props.color };
}
render() {
return (
<div style={{ color: this.state.color }}> Hello World! </div>
)
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { color: 'red' };
}
render() {
return (
<div>
<Child color={this.state.color} />
<button onClick={() => this.setState({ color: 'green'})}>
Change Color
</button>
</div>
)
}
}
export default App;

您的构造函数运行一次,然后将其初始值复制到状态中,该状态永远不会改变。这里有两个选项:

  1. 将按钮移动到组件中,并使其设置组件自身的状态:
render() {
return (
<>
<div style={{ color: this.state.color }}> Hello World! </div>
<button onClick={() => this.setState({ color: 'green'})}>
Change Color
</button>
)
}
  1. 直接使用道具:
<div style={{ color: this.props.color }}> Hello World! </div>

最新更新