反应处理表单提交

React handle form submit

我正在尝试在 React/Redux 中创建一个表单。现在我只希望表单在提交表单时触发我的函数 handleSubmit。但是目前看起来该功能是在页面加载时立即触发的...

export default class AssetsAdd extends React.Component {

  componentDidMount() {
    console.log(this)
  }

  handleSubmit(event) {
    if (this.refs.titleInput !== '') {
      event.preventDefault();
      var asset = {
        date: '',
        title : this.refs.titleInput.value,
        id : '',
        type: this.refs.typeInput.value
      }

      return this.props.dispatch(addAsset(asset))
    }


  }

  render() {
    return (
      <div>
        <Row>
          <Portlet title='New Asset' form>
            <Form horizontal onSubmit={this.handleSubmit}>
              <FormGroup>
                <Label text='Title' size='3' />
                <Input ref="titleInput" placeholder='Enter asset title' size='4'/>
              </FormGroup>
              <FormGroup>
                <Label text='Type' size='3' />
                <Input ref="typeInput" placeholder='Enter asset type' size='4'/>
              </FormGroup>
              <FormGroup>
                <Label text='Description' size='3' />
                <Input ref="descriptionInput" placeholder='Enter asset description' size='4'/>
              </FormGroup>
              <FormGroup>
                <Label text='Documentation' size='3' />
                <Input ref="documentationInput" placeholder='Enter documentation URL' size='4'/>
              </FormGroup>
              <FormActionBar>
                <SubmitButton value='Submit'/>
                <CancelButton value='Cancel'/>
              </FormActionBar>
            </Form>
          </Portlet>
        </Row>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    assets: state.assets
  };
}

export const AssetAddContainer = connect(mapStateToProps)(AssetsAdd);

我知道其余代码还不完全正确,但我现在主要关心的只是在正确的时刻触发 onSubmit 操作。

提前致谢!

您需要将 handleSubmit 作为道具传递

 <SubmitButton value='Submit' onSubmit={this.handleSubmit.bind(this)}/>

然后将该道具分配给 SubmmitButton 组件的渲染函数上的按钮。

// submmit button component @render method

<button onClick={this.props.onSubmit} >Submit</button>

您似乎没有绑定您的 handleSubmit

来自the docs

Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance.

你有三个选择

  1. 添加构造函数并在那里进行绑定(推荐):

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

  2. 直接绑定:

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

  3. 使用箭头=>函数

    onSubmit={() => this.handleSubmit}