javascript – React句柄表单提交

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

内容简介:翻译自: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


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

查看所有标签

猜你喜欢:

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

BLOG启示录

BLOG启示录

胡嘉玺 / 清华大学出版社 / 2010-7 / 48.00元

《BLOG启示录:WordPress博客建设与经营》分三大部分,共17章。第一部分(1~5章)主要是介绍Web 2.0、博客,以及LAMP的安装和架设,更有完整的主机、域名、DNS、WordPress安装、申请、交费等步骤,读者即使对计算机、主机、网络、域名等知识完全不懂,也可以依照《BLOG启示录:WordPress博客建设与经营》的步骤来落实整个WordPress基础建设的架构及安装。 ......一起来看看 《BLOG启示录》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

MD5 加密
MD5 加密

MD5 加密工具

SHA 加密
SHA 加密

SHA 加密工具