反应如何在调用OnSubmit时与组件结合



在我的组件中,我正在尝试使用组件的处理和handlesubmit函数

如果我像表单示例那样渲染,

    <form onSubmit={this.handleSubmit}>
      <input type="text" value={this.state.value} onChange={this.handleChange} placeholder="Enter new title"/>
      <input type="submit" value="Submit" />
    </form>

在onChange()中, this不会绑定到组件,我无法调用 this.setState,所以我用onChange = {()=> this.handlechange}。

对于onSubmit(),我有相同的绑定问题,但是当我绑定它时,没有调用处理程序,并且页面被重新加载。提交时绑定到组件的正确方法是什么?

tia

完整示例:

class CbList extends React.Component {
  constructor() {
    super();
    this.state = {
      newTitle: '',
      list: []
    };
  }
  handleChange(event) {
    this.setState(Object.assign({},
                                this.state,
                                { newTitle: event.target.value }));
  }
  handleSubmit(event) {
    this.addBlock(this.state.newTitle);
    event.preventDefault();
    return false;
  }
  render() {
    return (
      <div className="cb-list">
        <div>
          <form onSubmit={() => this.handleSubmit}>
            <input type="text" value={this.state.value} onChange={() => this.handleChange}
                   placeholder="Enter new title"/>
            <input type="submit" value="Submit" />
          </form>
        </div>
      </div>
    );
  }
  addBlock(title) {
    let updatedList = this.state.list.concat({ title: title });
    this.setState({ list: updatedList })
  }
};
$(function() {
  ReactDOM.render(<CbList/>, $('#home').get(0));
});

您忘了调用功能:

onSubmit={()=>this.handleSubmit}

应该是

onSubmit={()=>this.handleSubmit()}

或,只需传递对函数的引用:

onSubmit={this.handleSubmit}

但是您需要在构造函数中绑定函数(如表单示例链接中显示):

this.handleSubmit = this.handleSubmit.bind(this);

您需要在构造函数上进行 bind事件处理程序,以便可以在其他事件中使用它们。

constructor(props) {
  super(props)
  this.handleSubmit = this.handleSubmit.bind(this)
  this.handleChange = this.handleChange.bind(this)
}

另外,使用当用作props时,您不需要箭头功能。

<form onSubmit={this.handleSubmit}>
  <input
    type="text"
    value={this.state.value}
    onChange={this.handleChange}
    placeholder="Enter new title"
  />
  <input type="submit" value="Submit" />
</form>

最新更新