使用 redux-form 7 将自定义道具传递给组件

Passing custom props to component with redux-form 7

我正在使用以下库

"@material-ui/core": "^3.0.3",
"react": "^16.5.0",
"redux": "^4.0.0",
"redux-form": "^7.4.2",

如何将自定义道具传递给我的 component 属性 的 redux-form <Field />

根据 redux-form 中的 this example,我在下面的所有内容都应该有效,但它没有将 multiline={true}rows={2} 道具拉入 <TextField /> 组件。

我不确定它应该如何工作,因为我是 javascript 的新手。任何帮助,将不胜感激。

PostForm.js

import React from 'react'
import { Link, withRouter } from 'react-router-dom';
import { reduxForm, Field } from 'redux-form';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField'


class PostForm extends React.Component {

  renderTextField = ({ input,
                      label, 
                      meta: { error, touched } },
                      ...custom) => {
    return (
        <TextField
          name={label}
          label={label}
          {...input}
          {...custom}
        />
    );
  };


  onSubmit(event) {
    event.preventDefault();

    const { submitPost, history, formValues } = this.props;

    submitPost(formValues.values, history);
  }

  render() {
    <form onSubmit={this.onSubmit.bind(this)}>

      <Field 
        name="title"
        component={this.renderTextField}
        label="Title"
      />
      <Field 
        name="body"
        component={this.renderTextField}
        label="Body"
        multiline={true}
        rows={2}
      />
      <div className={classes.buttonContainer}>
        <Button to="/posts" component={Link} className={classes.button} color='secondary'>
          Cancel
        </Button>
        <Button type='submit' className={classes.button} color='primary'>
          Next
        </Button>
      </div>
    </form>
  }
}

export default reduxForm({
  validate,
  form: 'postForm',
  destroyOnUnmount: false
})(PostForm)

要呈现多行字段,您需要传递 multiLine={true}(注意驼峰式大小写 - 这很重要)。这是基于从 https://github.com/erikras/redux-form-material-ui 链接的文档,看起来像旧版本。根据较新的文档,似乎 multiline 都是小写的(为了后代的缘故,将其保留在这里)。

更新

此外,...custom 在大括号之外。应该是

renderTextField = ({ input, label, meta: { error, touched } , ...custom })

关于 Field 如何向下传递 props 的一些信息 - 这不足以涵盖此答案中的所有内容,但我可以提供一些建议来帮助您入门。

<Field ... /> 是 JSX 表示法。虽然 JSX 使阅读和编写 HTML 结构变得容易,但 [React actually doesn't need JSX][1]。在内部,它们都编译为纯 JS 函数(使用 React.createElement 和其他工厂函数)。

之后,传递...custom等只是ES6中引入的rest/spread operators。它们是快捷方式,你也可以在没有它们的情况下使用 React(这意味着你可以只使用 ES5 语法)。