[英]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",
如何將自定義道具傳遞給redux-form <Field />
component
屬性?
根據這個來自redux-form的示例 ,我下面的所有內容都應該起作用,但它不是將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
如何傳遞道具的一些知識-不足以涵蓋此答案中的所有內容,但我可以提供一些指導以幫助您入門。
<Field ... />
是JSX表示法。 盡管JSX使讀取和編寫HTML構造變得容易,但是[React actually doesn't need JSX][1]
。 在內部,它們都編譯為純JS函數(使用React.createElement
和其他工廠函數)。
在那之后,傳遞...custom
等只是ES6中引入的rest / spread運算符 。 它們是快捷方式,您也可以在沒有它們的情況下使用React(這意味着您可以僅使用ES5語法)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.