在调用 onSubmit 时react如何绑定到组件

IT技术 javascript reactjs
2021-05-17 03:38:50

在我的组件中,我试图调用组件的 handleChange 和 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} 绑定。

for 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));
});
2个回答

你忘了调用函数:

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)
}

此外,当使用 then 作为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>