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 dont 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


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

查看所有标签

猜你喜欢:

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

程序的力量

程序的力量

甄贞 / 法律出版社 / 2002-3 / 21.00元

本书所谈及的话题概括了刑诉法学研究领域的方方面面,既有对每性、广泛性、前瞻性的宏观学科前沿问题的把握;又有实践性、直观性、详细性的个案分析和具体程序操作问题之探讨等。一起来看看 《程序的力量》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

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

HEX CMYK 互转工具