地图值react.js

时间:2019-08-14 11:05:52

标签: javascript reactjs

我在尝试使用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>
));

2 个答案:

答案 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时有效