redux-form:动态定义 handleSubmit

redux-form: Dynamically defining handleSubmit

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

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

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

Form.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.