简体   繁体   English

反应:渲染状态数组

[英]React: Rendering state array

I'm making a search form with React including a multiple select tag which adds selected options into a state as an array.我正在使用 React 制作一个搜索表单,其中包含一个多选标签,该标签将所选选项作为数组添加到状态中。

How do I successfully render selected items as a removable buttons into a box div?如何将所选项目作为可移动按钮成功渲染到框 div 中?

class Search extends React.Component {
    constructor(props) {
        super(props)
        this.state = { selected: [] }
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange = e => {
        let item = e.target.value
        let selected = this.state.selected
        if (selected.includes(item)) {
            return null
        } else {
            selected.push({ item })
            this.setState({ selected: item })
        }
    }

    render() {
       const items = [ item1, item2, item3,... ]

    return(
       .....
       <select
           multiple={true}
           value={this.state.value}
           onChange={this.handleChange}>
           {items.map(item => (
              <option
                 key={item}
                 value={item}>
                 {item}
             </option>
           ))}
      </select>
      <div className="box">
      </div>

By doing this,通过做这个,

selected.push({ item })

You are actually pushing object to array, which should be just您实际上是将对象推送到数组,这应该只是

selected.push( item )  //push item directly

Also you are setting state incorrectly,您还错误地设置了状态,

this.setState({ selected: item })

You should only have,你应该只有,

this.setState({ selected })

And finally you can iterate over selected array like this,最后你可以像这样迭代选定的数组,

<div className="box">
  { this.state.selected && this.state.selected.length > 0 && this.state.selected.map(selected=> <button key={selected}>{selected}</button>)
  }
</div>

Demo演示

You can use the same approach as with your select .您可以使用与select相同的方法。

For example:例如:

<div className="box">
   { 
     this.state.selected.map(item => (
        <Button ...>
     ))
   }
</div>

Make the item as object将项目作为对象

const items = [ {item1:item1, isSelected: false}, {item2, isSelected: false},... ]

And when item select - toggle isSelected to true, and make some button if the item object.isSelected === true当项目选择时 - 将 isSelected 切换为 true,如果项目 object.isSelected === true,则制作一些按钮

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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