React Select组件状态变更后下拉选项未更新显示如何解决?
react-select options更新后下拉显示为空解决方案
问题根因
你的实现思路本身没有问题,出现选项不更新的核心原因是对react-select的API使用错误:
- 控制输入值的prop名称错误:react-select用于绑定输入框值的prop是
inputValue,你传的input属于无效prop,导致组件内部维护的输入值和你state中的input不一致 getOptionLabel用法错误:该API要求返回纯字符串,用于输入内容匹配、选中值展示等内部逻辑,你返回了自定义的table React节点,组件内部做本地过滤时无法匹配到有效字符串,直接把所有选项过滤为空- 默认开启了前端过滤:你通过后端请求返回的已经是过滤后的结果,react-select默认还会基于输入值做一次本地过滤,多余的二次过滤也会导致选项被误筛
修复步骤
- 修正Select组件的prop配置:
- 把无效的
input={this.state.input}改为inputValue={this.state.input} - 添加
filterOption={() => true}关闭前端本地过滤 - 把自定义选项渲染的逻辑从
getOptionLabel移到components.Option中,getOptionLabel仅返回纯字符串
- 把无效的
- 调整自定义选项渲染方法的入参,适配react-select的自定义组件规则
- 补充未初始化的状态变量(你的代码中
this.state.target_model没有定义,若来自props请改为this.props.target_model)
完整修改后的核心代码
Select组件部分
<Select placeholder={this.state.input || ''} options={this.state.options} inputValue={this.state.input} // 修正prop名 filterOption={() => true} // 关闭前端过滤 onFocus={() => this.loadOptions(this.state.input)} onInputChange={this.loadOptions.bind(this)} value={curr_value} getOptionLabel={option => option.label} // 返回纯字符串用于匹配 components={{ Option: this.renderOption.bind(this) }} // 自定义选项渲染 onChange={this.onSingleSelect.bind(this)} />
renderOption方法部分
// 自定义Option组件接收的参数中,data字段对应你的option对象 renderOption({ data }){ if(!data || !this.props.known_alias_list) return null return ( <table className='highlight-on-hover' style={{width: '100%'}}><tbody><tr> <td>{data.label} {Object.keys(this.props.known_alias_list).includes(data.value.id) && ' ('+this.props.known_alias_list[data.value.id]+')'}</td> {data.value.image && <td><ObjectImage picture={data.value.image} style={data.value.username ? {height: '25px', width: '25px', float: 'right', borderRadius: '50%'} : {height: '25px', width: '25px', float: 'right'}}/></td> } </tr></tbody></table> ) }
修改完成后options更新时下拉列表会直接同步渲染,不需要重新聚焦触发。
内容的提问来源于stack exchange,提问作者Anne Haley
相关产品推荐
相关产品推荐

