在react中传递变量

时间:2018-11-04 21:39:56

标签: reactjs state

我有他的代码,我尝试将变量传递给handleclick fcn并将状态设置为该变量:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Initial State'
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(temp) {
    this.setState({
      name:temp
    });
  }
  render() {
    return (
      <div>
        <button onClick={this.handleClick('name')}>Click Me</button>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
};

这是行不通的,如果可以的话,有人可以解释如何传递变量并将状态设置为它吗?

1 个答案:

答案 0 :(得分:2)

通过编写this.handleClick('name'),您可以直接在渲染上调用handleClick函数。您想给onClick道具提供一个功能,该功能将在点击时调用。

示例

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "Initial State"
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(temp) {
    this.setState({
      name: temp
    });
  }
  render() {
    return (
      <div>
        <button onClick={() => this.handleClick("name")}>Click Me</button>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
}

ReactDOM.render(<MyComponent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>