react-select - 如何仅使用 react-select onChange 事件和 value 道具中的值?
问题描述
我尝试在我的 reactjs 应用程序中使用 react-select,但是 onChange 事件有问题。onChange 应该发送两个参数。第一个应该是选定值,但不是选定值,而是整个选项项作为选定值传递。
例如
- 我有一系列选项,例如
options=[{ id: '1', name: 'A'},{ id: '2', name:'B'}]
- 我设置
getOptionValue = (i) => i.id;
和getOptionLabel = (i)=>i.name;
- When select the second item
onChange(value)
is passed the second option as thevalue
argument ({id:'2',name:'B'}
) instead of the value of the second option ('2'
).
这种行为与大多数输入组件不一致。我希望onChange
传递项目的值,而对于项目本身,我希望有另一个类似onItemSelected
或类似的事件。
另外,当我设置value={'2'}
(受控组件)时,该组件不显示所选项目。
我必须说我将 AsyncSelect 与 loadOptions 一起使用。
我怎样才能让它只使用简单的值,而不是选项对象?
如果这不能发生,我必须放弃 react-select 以获得另一个类似的组件。
解决方案
AFAIK 目前没有办法让 React-Select 在内部只使用值。我在我的应用程序中所做的是实现一个层来检索下降的对象,并提取上升的值。像这样的东西(这是简化的,您可能需要更多的验证或处理,具体取决于您的应用程序):
const Select extends Component {
handleChange(newSelected) {
// this.props.handleChange is your own function that handle changes
// in the upper scope and receives only the value prop of the object
// (to store in state, call a service, etc)
this.props.handleChange(newSelected.value);
}
render() {
// Assuming you get the simple value as a prop from your store/upper
// scope, so we need to retrieve the option object. You can do this in
// getDerivedStateFromProps or wherever it suits you best
const { options, value } = this.props;
const selectedOption = options.find(option => option.value === value)
<ReactSelect
options={options}
value={selectedOption}
onChange={this.handleChange}
{...props}
/>
}
推荐阅读
- java - 如何仅将 Spring Converter 用于某些控制器?
- python - 用python写入excel文件
- python - 在python中导入更新的包
- asp.net-core - CurrentDepth (32) 等于或大于最大允许深度 32
- javascript - 加载“grunt-karma.js”任务...错误 >> SyntaxError: Unexpected identifier
- c - 我如何理解 -O3 的优化?
- sql - postgresql自连接查询条件不返回重复结果
- django - Django Rest 框架中的嵌套序列化程序
- django - 获取 html 文件中查询集的第二项(Django)
- regex - Atom 编辑器正则表达式从每次文本中删除括号