React Component未在setState上重新呈现

时间:2019-09-22 18:10:44

标签: javascript html css reactjs jsx

我有以下代码。我正在使用setState方法(this.setState({ country: "", offset: "" });)设置状态,并且不会导致render()方法本身重新呈现。

  state = { country: "", offset: "" };
  onClicked = () => {
    console.log("Fine Click away");
    // Get the call back from props
    let country = this.state.country;
    let offset = this.state.offset;
    this.setState({ country: "", offset: "" });
    const callback = this.props.onpress;

    if (callback) {
      callback(country, offset);
    }
  };
getTheCountryName = event => {
    this.setState({ country: event.target.value });
  };
  getTheOffSet = e => {
    this.setState({ offset: e.target.value });
  };
render() {

    const Caption = this.props.caption;
    return (
      <div>
        <br></br>
        <br></br>
        <div>Please enter the name of country and offset:</div>
        <input
          placeholder="Name of Country"
          onChange={this.getTheCountryName}
        />
        <input placeholder="offset" onChange={this.getTheOffSet} />
        <br></br>
        <br></br>
        <button className="rectangular-button" onClick={this.onClicked}>
          <div className="caption">{Caption}</div>
        </button>
      </div>
    );
  }
}```

1 个答案:

答案 0 :(得分:2)

以任何容量重置状态都不会触发输入值的更新,因为您实际上并没有在返回的JSX中使用状态。下面的代码会将这些值提供给输入,以便在您更改状态时更新它们。您可以在React here中阅读有关表单和受控输入的信息:

class App extends React.Component {
   state = { country: "", offset: "" };
  onClicked = () => {
    console.log("Fine Click away");
    // Get the call back from props
    let country = this.state.country;
    let offset = this.state.offset;
    this.setState({ country: "", offset: "" });
    const callback = this.props.onpress;

    if (callback) {
      callback(country, offset);
    }
  };
getTheCountryName = event => {
    this.setState({ country: event.target.value });
  };
  getTheOffSet = e => {
    this.setState({ offset: e.target.value });
  };
render() {

    const Caption = this.props.caption;
    return (
      <div>
        <br></br>
        <br></br>
        <div>Please enter the name of country and offset:</div>
        <input
          placeholder="Name of Country"
          onChange={this.getTheCountryName}
          value={this.state.country}
        />
        <input value={this.state.offset} placeholder="offset" onChange={this.getTheOffSet} />
        <br></br>
        <br></br>
        <button className="rectangular-button" onClick={this.onClicked}>
          <div className="caption">Reset</div>
        </button>
      </div>
    );
  }
}

相关问题