.NET Core项目引入react-select报错Select未定义如何解决
报错原因
- CDN引入的react-select不会自动注册全局
Select变量,所有导出内容都挂载在window.ReactSelect全局对象下,直接调用Select自然会报未定义。 - react-select的API用法和原生select不同,不支持嵌套
<option>子元素,需要通过属性传递配置和选项。
解决方案
1. 全局获取Select组件
在你写JSX的代码最上方,先从全局对象中取出Select组件:
const Select = window.ReactSelect.default;
如果要使用其他衍生组件比如可创建选项的Select,对应取window.ReactSelect.Creatable即可。
2. 修正组件用法
react-select多选模式下value为数组格式,onChange回调直接返回选中项数组,选项通过options属性传入,不需要写<option>标签,调整后的代码如下:
// 先把你的industries数据转换为react-select要求的格式 const industryOptions = industries.map(industry => ({ value: industry.businessSectorId, label: industry.name })); // 组件渲染部分 <div className="col-lg-6"> <label className="font-weight-bold text-dark col-form-label form-control-label text-2"> Industries you are interested in </label> <Select id="ddlIndustry" value={industry || []} className="form-control multi-select" isMulti onChange={selectedOptions => mutipleSelect(selectedOptions)} options={industryOptions} placeholder="-- Select Industry you are interested in --" /> </div>
3. 确认加载顺序
你当前_Layout.cshtml的依赖加载顺序是正确的,只要保证react、react-dom加载顺序早于react-select即可,无需调整。
内容的提问来源于stack exchange,提问作者CH-siko
相关产品推荐
相关产品推荐

