在react中的multiselect中设置默认值

时间:2019-11-13 02:11:49

标签: javascript reactjs react-bootstrap-typeahead

我使用React bootstrap Typeahead库(https://github.com/ericgio/react-bootstrap-typeahead)。我的问题是,基于索引this.state.todo,我需要在this.state.todos内部查找具有给定索引的对象。在多选中将找到的对象的名称显示为默认值。

此处演示:https://stackblitz.com/edit/react-rsfpup

class App extends Component {
  constructor() {
    super();
    this.state = {
      todos: [{id:1, name: 'Paul'}, {id:2, name: 'Martin'}, {id:3, name: 'Jacob'}],
      todo:[1, 3],
      selectedItems: []
    };
  }

  handleSelect = items => {

    this.setState({ selectedItems: items });
  };

  render() {

    return (
      <div>
        <Todos 
          todos={this.state.todos}
          todo={this.state.todo}
          handleSelect = {this.handleSelect}
        />
      </div>
    );
  }
}

class Todos extends Component {
   constructor(props) {
    super(props);

  }

  render() {
    var tempArr = this.props.todos.filter(item => !this.props.todo.includes(item));



    return (
      <div>
        <Typeahead
          id={'example4'}
          labelKey="name"
          multiple
          selected={tempArr}
          options={this.props.todos}
          onChange={this.props.handleSelect}
        />
      </div>
    );
  }
}

2 个答案:

答案 0 :(得分:2)

我认为您正在寻找这个

let selected = this.state.todos.map( (todo, index) => {
   if(this.state.todo.includes(index)){  //compare based on index
      return todo
   }
})

如果要基于id中的this.state.todos进行比较,

let selected = this.state.todos.map( (todo, index) => {
   if(this.state.todo.includes(todo.id)){  //compare based on id in this.state.todos
      return todo
   }
})

更新

根据您的演示示例,您只需要在selectedItems组件中设置App,并将其传递给Todos组件。

componentDidMount(){
    //Based on index
    this.setState({
      selectedItems: this.state.todos.filter( (todo, index) => this.state.todo.includes(index))
    })

    //Based on id in this.state.todos
    // this.setState({
    //   selectedItems: this.state.todos.filter( (todo, index) => this.state.todo.includes(todo.id))
    // })
}

注意:,您需要在此处使用map,而不是filter

selectedItems传递到Todos组件,

<Todos 
    todos={this.state.todos}
    todo={this.state.todo}
    handleSelect = {this.handleSelect}
    selectedItems = {this.state.selectedItems}  //Pass selectedItems here
/>

Todos组件中,您需要使用selectedItems

<Typeahead
    id={'example4'}
    labelKey="name"
    multiple
    selected= {this.props.selectedItems}  //Use selectedItems here
    options={this.props.todos}
    onChange={this.props.handleSelect}
/>

Demo

答案 1 :(得分:0)

我认为问题是因为todos是一个对象数组,而todo是一个整数数组,因此,当您执行过滤器时,它将不起作用,您将不得不使用todos.id。例如:

var tempArr = this.props.todos.filter(item => !this.props.todo.includes(item.id));
相关问题