首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >redux-form:动态定义handleSubmit

redux-form:动态定义handleSubmit
EN

Stack Overflow用户
提问于 2015-11-03 21:02:10
回答 1查看 4.2K关注 0票数 3

由于我对反应生态系统非常陌生,我的描述和做事方式可能还很遥远,但我希望你能关注我的问题。

我有一个父组件,它从路由器注入一个表单,并将状态和动作创建者映射到属性。

Container.js

代码语言:javascript
复制
import * as actionCreators from "../actionCreators";

export default class ComponentA extends React.Component {

  render() {
    return (
      <div className="ComponentA">
        {this.props.children} //<--Form
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    listItems: state.get("listItems")
  };
}

export const Container = connect(mapStateToProps, actionCreators)(ComponentA);

使用{this.props.children}呈现的组件如下所示。

Form.js

代码语言:javascript
复制
class Form extends React.Component {

  static propTypes = {
    fields: PropTypes.object.isRequired,
    handleSubmit: PropTypes.func.isRequired
  };   

  render() {
    const { fields: {title, description}, handleSubmit} = this.props;
    return (
      <div className="create-project-form">
        <h1>Create Project</h1>
        <form onSubmit={handleSubmit}>
          <label htmlFor="title">Title</label>
          <input type="text" name="title" id="title" className="form-control"/>
          <label htmlFor="description">Description</label>
          <textarea name="description" id="" cols="30" rows="10" className="form-control"></textarea>
          <button className="btn btn-danger" onClick={handleSubmit}>Create</button>

        </form>
      </div>
    )
  }
}

export default connectReduxForm({
  form: "from",
  fields: ["title", "description"]
})(Form);

路由器

代码语言:javascript
复制
const routes = <Route component={App}>
  <Route path="/" component={Container}/>
  <Route path="/a" component={Container}>
    <Route path="/a/create" component={Form}/>
  </Route>
</Route>;

render(
  <div>
    <Provider store={store}>
      <Router>{routes}</Router>
    </Provider>
  </div>,
  document.getElementById("content"));

问题是handleSubmit不是没有定义的,但它不是我的行为。实际上,我并不期望它被神奇地设置为正确的actionCreator,但是如何传递函数呢?我尝试了动作名而不是handleSubmit,但是函数没有定义。我看到的每个示例都将handleSubmit函数手动传递到表单组件中,但我无法做到这一点,因为表单是由路由器设置的。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-03 21:20:25

有两件事:

  1. 您需要将字段信息传递给您的<input>

<input type="text" {...title} // <-------- that (it contains the "name" prop) className="form-control"/>

  1. 您可以将任何匿名函数传递给handleSubmit

<form onSubmit={handleSubmit(data => { // do your submit stuff here and return a Promise if you want the // this.props.submitting flag to be set for the duration of the promise })}>

有帮助吗?See also

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33509007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档