You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 styleChange function doesn't handle target colors
    Right now, your styleChange just sets state to the current color, which does nothing. It also shouldn't be defined inside the render method (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 a style variable 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 inside render, this didn'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 button onClick to 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 of style={color: red} — unquoted red would be treated as an undefined variable).

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:21:47