如何使用 Redux 在子组件中触发表单提交? [英] How to trigger a form submit in child component with Redux?

查看:36
本文介绍了如何使用 Redux 在子组件中触发表单提交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的表单组件:

I have a Form component like this:

var React = require('react'),
  ReactRedux = require('react-redux');


var Form = React.createClass({
  render: function(){
    return (
      <form onsubmit={this.onsubmit} action={this.props.action}>
      {this.props.children}
      </form>
    );
  },
  // Method for parent component to call
  submit: function() {
    // do submission and return Promise so caller can take actions
  },
  onsubmit: function(e) {
    // validation, make requests, etc
  }
});

function mapStateToProps(state) {
  return state;
}

module.exports = ReactRedux.connect(mapStateToProps)(Form);

在我的组件渲染中,我有 <Form id="paymentform" ref="form" action="/self">.

Inside my render of a component I have <Form id="paymentform" ref="form" action="/self">.

我不能做 this.refs.form.submit(); 因为 this.refs.form 指向连接器.据我所知,连接器是减速器更新道具的漏斗,但是这样做不能触发对 submit 的调用.

I can't do this.refs.form.submit(); because this.refs.form points to the Connector. As I understand it, Connectors are the funnels for reducers to update props, however doing that can't trigger a call to submit.

用例基本上是让表单从另一个操作提交,这将启动表单组件应该执行的操作,例如验证和 XHR 请求.

The use case is basically to have the form submit from another action, which will kick off what the Form component is supposed to do such as validation and XHR requests.

我可以做 React.findDOMNode(this.refs.form).submit() 但这并不能回答从外部击中组件方法的实际问题.

I can do React.findDOMNode(this.refs.form).submit() but that doesn't answer the actual question of hitting a component method from outside.

我在这里做错了什么?

推荐答案

如果需要,可以获取封装的组件实例,使用getWrappedInstance:

You can get the wrapped component instance, if necessary, with getWrappedInstance:

this.refs.form.getWrappedInstance().submit()

这篇关于如何使用 Redux 在子组件中触发表单提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆