javascript – React句柄表单提交

栏目: 服务器 · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/38262148/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.

the docs 开始:

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

你有三个选择

>添加一个构造函数并在那里进行绑定(推荐):

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

>直接绑定:

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

>使用arrow =>功能

onSubmit = {()=> this.handleSubmit}

翻译自:https://stackoverflow.com/questions/38262148/react-handle-form-submit


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

你不知道的JavaScript(中卷)

你不知道的JavaScript(中卷)

[美] Kyle Simpson / 单业、姜南 / 人民邮电出版社 / 2016-8 / 79.00元

JavaScript这门语言简单易用,很容易上手,但其语言机制复杂微妙,即使是经验丰富的JavaScript开发人员,如果没有认真学习的话也无法真正理解。本套书直面当前JavaScript开发人员不求甚解的大趋势,深入理解语言内部的机制,全面介绍了JavaScript中常被人误解和忽视的重要知识点。本书是其中卷,主要介绍了类型、语法、异步和性能。一起来看看 《你不知道的JavaScript(中卷)》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具