单击按钮时,SetState不会更新

时间:2019-11-27 05:11:09

标签: asp.net reactjs model-view-controller state setstate

我正在尝试使用setState来更改按钮单击时的颜色。但是单击按钮时它不会更改状态。我已经附加了App.jsIndex.html文件。

当我在Visual Studio代码上尝试时,它可以工作。但在使用asp.net mvc的Visual Studio 2019中不起作用。我想用带有reactjs集成项目的Asp.net mvc尝试一下

class Business extends React.Component {
    constructor(props) {
        super(props);
        this.state = {color: "red" };
    }
 
    changeColor = () => {
        this.setState({ color: "blue" });
    }
    render() {
        return (
            <div>
                <h1>My Favorite Color is {this.state.color}</h1>
                <button type="button" onClick={this.changeColor}>Change Color</button>
            </div>
        );
    }
}
@using React.Web.Mvc

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.React("Business", new
    {
      


    })

1 个答案:

答案 0 :(得分:0)

请使用以下代码更新您的代码:

class Business extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
        color: "red"
      };
  }
 
  changeColor = () => {
      /*Please remove alert*/
      alert('Working');
      this.setState({ color: "blue" });
  }
  render() {
      return (
          <div>
              <h1>
                My Favorite Color is {this.state.color}
              </h1>
              <button type="button" onClick={this.changeColor}>Change Color</button>
          </div>
      );
  }
}
export default Business;