【问题标题】:Setting the default value in multiselect in react在反应中设置多选的默认值
【发布时间】:2025-12-24 08:55:16
【问题描述】:

我使用 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>
    );
  }
}

【问题讨论】:

  • 您好 Umbro,请检查我的解决方案,如果有帮助请告诉我。

标签: javascript reactjs react-bootstrap-typeahead


【解决方案1】:

我想你正在寻找这个,

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

如果您想在this.state.todos 中根据id 进行比较,

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

更新

根据您的演示示例,您只需在您的App 组件中设置selectedItems,并且需要将其传递给您的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))
    // })
}

注意:这里需要使用filter,而不是map

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

【讨论】:

    【解决方案2】:

    我认为问题是因为 todos 是一个对象数组,而 todo 是一个整数数组,所以当你做过滤器时,它不起作用,你必须使用 todos.id。例如:

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

    【讨论】: