我将如何遍历数组并根据值显示输入框?

How would I iterate through array and display input boxes based on values?

我是 React 新手,我创建了一个像这样的 json:

const parent: [{name:will, kids['child1', 'child2']}
              {name: 'kia' kids['child1']}
              {name: 'jim', kids['child1', 'child2']}]

我无法使用此 json 访问这些值。我正在尝试创建一个包含数组中所有名称值的列表,以便我可以将其放入下拉列表中,但是当我尝试在我的 console.log[=12= 中打印列表时,我不断收到 'undefined' ]

此外,当我单击名称时,我想根据所选名称的孩子列表的长度创建输入框。因此,例如,如果我在下拉列表中单击 'will',将形成两个输入框,其中 'child1' 和 'child2' 都在两个输入框中。但是如果我点击“起亚”,将形成一个输入框,里面已经有“child 1”。有任何想法吗?我在访问这些值时遇到很多问题。

这是我目前的尝试:

import Dropdown from 'react-dropdown';


 parent: [{name:will, kids['child1', 'child2']}
              {name: 'kia' kids['child1']}
              {name: 'jim', kids['child1, 'child2']}]


 
class AppEX extends React.Component {
constructor() {
    super();
    this.state = {
      parentnamelist: []
      parentname: null
      

    }
  }
  
 render() {
namelist: []
this.state.parent.map((e, key) => {
       namelist.push({value:e.name,label:e.name})
  })
        return (

<select name="select" onChange={this.namelist}>
  {num.map(function(n) { 
      return (<option value={n} selected={this.state.selected === n}>{n}</option>);
  })}
</select>

有什么想法吗?

这里有各种各样的问题。

  1. parent 列表格式不正确,应该如下所示:
const parent = [
  { name: "will", kids: ["child1", "child2"] },
  { name: "kia", kids: ["child1"] },
  { name: "jim", kids: ["child1", "child2"] }
]
  1. 您在 render 方法中使用 map 将 parent 个名称推送到名为 namelist 的新列表中,但您必须使用 forEachmap 转换列表,而 forEach 对每个成员做一些事情。
const namelist = [];
this.state.parent.forEach(e => {
  namelist.push({ value: e.name, label: e.name });
});
  1. 现在render returnonChange 处理程序必须是一个函数,因为你想跟踪选定的 parent,我猜你想把它保存到你的状态:
handleParentChoice = e => {
  e.persist();
  this.setState({
    parentname: e.target.value
  });
};

然后

return (
  <div>
    <select name="select" onChange={this.handleParentChoice}>
      {namelist.map(n => (
        <option key={n.value} value={n.value}>{n.label}</option>
      ))}
    </select>
    <br />
    {this.state.parentname && // Shows below stuff only if parentname is not null
      this.state.parent
        .find(p => p.name === this.state.parentname) // Find the parent based on the saved name, then map the kids into input tags
        .kids.map(k => <input key={k} type="text" />)}
  </div>
);

此外,当你映射某些东西时,每个 child 应该有一个 key 道具。

See the code working here