简体   繁体   中英

Map value react.js

I am having a problem where I am trying use value in map. Is it possible to use value from state when mapping? How should I do it correctly?

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>
));

You just have to find the value corresponding to the label property:

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>
));

If I understand the question correctly, you could use your name property to access the state value by using the "bracket notation":

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>
));

This only works if the key of your state property is equal to the name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM