首页 > 解决方案 > 与 REACT (setState()) 斗争

问题描述

REACT 新手,问题很简单,有三个“颜色”按钮。单击一个时, h1 标记将更改为按钮颜色。h1 的默认值为黑色。

const root = document.getElementById("root");


class ChangeColors extends React.Component {
  constructor() {
    super();
    this.state = { color: "black" };
  }
  render() {
    const styleChange = () => {
      this.setState({ color: this.state.color })
    }
    return (
      <div>
        <h1 style={style}>Change My Colour!</h1>
        <p>
          <button onClick={this.styleChange} style={color: 
  red}>Red</button>
          <button onClick={this.styleChange} style={color: 
    blue}>Blue</button>
          <button onClick={this.styleChange} style={color: 
   green}>Green</button>
        </p>
      </div>
    );
  }
}

ReactDOM.render(<ChangeColors />, root);

标签: reactjsclassstatejsx

解决方案


您的代码中有很多语法错误,但这里有一个固定版本:https ://codesandbox.io/s/62row8358z


推荐阅读