React setState使用问题求助:点击按钮修改H1文本颜色功能异常
Hey there! Let's walk through the issues in your code one by one and fix them up so your color-changing functionality works as expected.
Key Issues in Your Code
The
styleChangefunction doesn't handle target colors
Right now, yourstyleChangejust sets state to the current color, which does nothing. It also shouldn't be defined inside therendermethod (it gets recreated on every render, which is inefficient). We'll move it to a class method and make it accept a color parameter.Invalid style reference on the H1 tag
You tried to use astylevariable that doesn't exist. Instead, directly map your component state to the H1's style with{{ color: this.state.color }}.Broken button onClick binding & style syntax
- You referenced
this.styleChange, but since the function was insiderender,thisdidn't point to it. Even if it did, the function had no way to know which color to apply. We'll use arrow functions in the buttononClickto pass the specific color to our handler. - Your button styles had invalid syntax: style values must be objects with quoted color strings (e.g.,
style={{ color: 'red' }}instead ofstyle={color: red}— unquotedredwould be treated as an undefined variable).
- You referenced
Fixed Code
const root = document.getElementById("root"); class ChangeColors extends React.Component { constructor() { super(); this.state = { color: "black" }; // Bind the handler to ensure `this` refers to the component instance this.styleChange = this.styleChange.bind(this); } // Class method to handle color updates styleChange(color) { this.setState({ color: color }); } render() { return ( <div> <h1 style={{ color: this.state.color }}>Change My Colour!</h1> <p> <button onClick={() => this.styleChange('red')} style={{ color: 'red' }}>Red</button> <button onClick={() => this.styleChange('blue')} style={{ color: 'blue' }}>Blue</button> <button onClick={() => this.styleChange('green')} style={{ color: 'green' }}>Green</button> </p> </div> ); } } ReactDOM.render(<ChangeColors />, root);
Alternative (No Manual Binding)
You can use class fields with arrow functions to skip manual binding in the constructor:
const root = document.getElementById("root"); class ChangeColors extends React.Component { // Initialize state directly with class fields state = { color: "black" }; // Arrow function automatically binds `this` to the component styleChange = (color) => { this.setState({ color }); } render() { return ( <div> <h1 style={{ color: this.state.color }}>Change My Colour!</h1> <p> <button onClick={() => this.styleChange('red')} style={{ color: 'red' }}>Red</button> <button onClick={() => this.styleChange('blue')} style={{ color: 'blue' }}>Blue</button> <button onClick={() => this.styleChange('green')} style={{ color: 'green' }}>Green</button> </p> </div> ); } } ReactDOM.render(<ChangeColors />, root);
内容的提问来源于stack exchange,提问作者TomK

