javascript - redux 形式 : Dynamically defining handleSubmit

标签 javascript reactjs react-router redux

由于我是 React 生态系统的新手,我的描述和做事的方式可能有很大偏差,但我希望你能关注我的问题。

我有一个父组件,它获取从路由器注入(inject)的表单并将状态和 Action 创建者映射到属性。

容器.js

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} 渲染的组件是以下形式。

表单.js

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);

路由器

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 函数手动传递到 Form 组件,但我不能这样做,因为 Form 是由 Router 设置的。

谢谢

最佳答案

两件事:

  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 .

关于javascript - redux 形式 : Dynamically defining handleSubmit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509007/

相关文章:

javascript - 无法在循环中设置未定义的属性 'innerHTML'

javascript - Angular,如何对窗口调整大小事件使用react

javascript - 为什么 Next.JS 在生产构建过程中自动删除 CSS?

javascript - 没有受限的全局变量

reactjs - 对更改作出 react Router v4

javascript - 如何删除自动生成id的父节点?如何指定那个id?

javascript - Angular2 从对象数组中获取值

reactjs - react native ,Redux : Fetch more/Load more

reactjs - 左右移动内容以跟随抽屉打开/关闭(Material-UI)

javascript - 将 props 传递给 React Router 4 中的组件