我在尝试使用map中的值时遇到问题。映射时是否可以使用状态值?我应该如何正确做?
const inputName=[
{id:1, label: 'Login',type:'text',name:'login',placeholder:'Enter login'},
{id:2, label: 'Password',type:'text',name:'password',placeholder:'Enter password'},
{id:3, label: 'Password',type:'password',name:'password2',placeholder:'Enter password again'},
{id:4, label: 'Name',type:'text',name:'firstName',placeholder:'Enter name'},
{id:5, label: 'Surname',type:'text',name:'lastName',placeholder:'Enter surname'},
{id:6, label: 'Position',type:'select',name:'role',option1:'Worker',option2:'Manager'},
]
/*My state*/
state = {
login: "",
password: "",
password2: "",
firstName: "",
lastName: "",
enable: true,
role: {
name: ""
}
};
/* My map */
/* How use value from state in my input mapping? */
const inputs = inputName.map(input => (
<FormGroup key={input.id}>
<Label>{input.label}</Label>
<Input
type={input.type}
name={input.name}
// value={} idk how get every value from state here
onChange={this.handleChange}
placeholder={input.placeholder}
>
<option>{input.option1}</option>
<option>{input.option2}</option>
</Input>
</FormGroup>
));
答案 0 :(得分:0)
您只需找到与label
属性相对应的值:
const inputs = inputName.map(input => (
<FormGroup key={input.id}>
<Label>{input.label}</Label>
<Input
type={input.type}
name={input.name}
value={this.state[input.label.toLowerCase()]} //this.state['login']
onChange={this.handleChange}
placeholder={input.placeholder}
>
<option>{input.option1}</option>
<option>{input.option2}</option>
</Input>
</FormGroup>
));
答案 1 :(得分:0)
如果我正确理解了这个问题,则可以使用“括号符号”来使用您的name属性访问状态值:
const inputs = inputName.map(input => (
<FormGroup key={input.id}>
<Label>{input.label}</Label>
<Input
type={input.type}
name={input.name}
value={this.state[input.name]} // access the value from the state
onChange={this.handleChange}
placeholder={input.placeholder}
>
<option>{input.option1}</option>
<option>{input.option2}</option>
</Input>
</FormGroup>
));
这仅在状态属性的key
等于name
时有效