[英]Dynamic Form in React with Redux-Form
我正在開發足球博彩系統。 我想動態制作一個表單,並通過redux-forms保持對象處於狀態。
我的基本實體是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
},
我想將其填寫在Redux-Form中,但會陷入制作它的最佳方式中。 我也希望每次用戶更改輸入上的值時,這都反映在State-Json中。
要動態創建表單,您將需要以其他方式構建數據。 您需要如下所示的fields對象(具有matchs id):
const fieldsObject = ['match1', 'match2', 'match3']
一個initialValues對象將如下所示:
const resultsObject = {
match1_home: 1,
match1_away: 3
}
等等。 然后,表單將基於initialValues和字段名稱來初始化其字段。 編碼:
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>
)
}
用法如下所示:
<MyForm initialValues={resultsObject} fields={fieldsObject} onSubmit={this.submitForm}/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.