我该如何解决“这在React JS应用中未定义”

时间:2018-12-13 11:21:16

标签: reactjs this state react-component

我有一个react组件,我想从Change()函数中更改值的状态,但是我收到一个错误消息,即“ this is undefined”。请让我通过。 下面是我的代码:

const Square = props => (
  <div>
    <button type="button" onClick={props.change}>
      Click Me
    </button>
  </div>
);

class Board extends Component {
  state = {
    value: ""
  };

  Change = () => {
    alert("YOU CLICKED A BUTTON");
    this.setState({
      value: "X"
    });
    console.log(this.state);
  };

  render() {
    var rows = [];
    for (var i = 0; i < 9; i++) {
      rows.push(
        <Square change={this.Change} value={this.state.value} key={i} />
      );
    }
    return <div className="mother">{rows}</div>;
  }
}

export default Board;

演示https://codesandbox.io/s/9zzqj0mqkr

0 个答案:

没有答案