[英]Dynamic Form in React with Redux-Form
Im developing a Soccer Betting system. 我正在开发足球博彩系统。 I want to make a form dynamically and keep the objects in the state with redux-forms. 我想动态制作一个表单,并通过redux-forms保持对象处于状态。
My basic entity is a Match: Who has a home_team, a away_team, and inputs with a home_result and a away_result. 我的基本实体是Match:谁有一个home_team,一个away_team,并带有home_result和away_result输入。
matches = [
{
name: 1,
type: "group",
home_team: 1,
away_team: 2,
home_result: null,
away_result: null,
date: "2018-06-14T18:00:00+03:00",
stadium: 1,
channels: [],
finished: false
},
{
name: 2,
type: "group",
home_team: 3,
away_team: 4,
home_result: null,
away_result: null,
date: "2018-06-15T17:00:00+05:00",
stadium: 12,
channels: [],
finished: false
},
I want to fill it in a Redux-Form, but get stuck in the best way to make it. 我想将其填写在Redux-Form中,但会陷入制作它的最佳方式中。 I want too that, every time a user changes the values on the input, this is reflected in the State-Json. 我也希望每次用户更改输入上的值时,这都反映在State-Json中。
To dynamically create a form, you will need to build your data differently. 要动态创建表单,您将需要以其他方式构建数据。 You need fields object that will look like this(with the matches id): 您需要如下所示的fields对象(具有matchs id):
const fieldsObject = ['match1', 'match2', 'match3']
And a initialValues object that will look like this: 一个initialValues对象将如下所示:
const resultsObject = {
match1_home: 1,
match1_away: 3
}
And so on. 等等。 Then, the Form will initial its fields based on the initialValues and the names of the fields. 然后,表单将基于initialValues和字段名称来初始化其字段。 The code: 编码:
const MyForm = (props) => {
const { handleSubmit, fields } = props;
return (
<form onSubmit={handleSubmit}>
{fields.map(match => (
<div key={match}>
<Field
name={`${match}_home`}
component="input"
/>
<Field
name={`${match}_away`}
component="input"
/>
</div>
))}
<button type="submit">Submit</button>
</form>
)
}
And the usage will look like this: 用法如下所示:
<MyForm initialValues={resultsObject} fields={fieldsObject} onSubmit={this.submitForm}/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.