我怎样才能只使用 react-select onChange 事件和 value prop 中的值?
How can I work with just values in react-select onChange event and value prop?
我尝试在我的 reactjs 应用程序中使用 react-select,但 onChange 事件出现问题。 onChange 应该发送两个参数。第一个应该是 selected 值,但不是 selected 值,整个选项项作为 selected 值传递。
例如
- 我有一系列选项,例如
options=[{ id: '1', name: 'A'},{ id: '2', name:'B'}]
- 我设置了
getOptionValue = (i) => i.id;
和getOptionLabel = (i)=>i.name;
- 当 select 第二项
onChange(value)
作为 value
参数传递给第二个选项时 ({id:'2',name:'B'}
) 而不是第二个选项的值 ('2'
).
此行为与大多数输入组件不一致。我希望 onChange
传递项目的值,对于项目本身,我希望另一个事件,如 onItemSelected
或类似的事件。
此外,当我设置 value={'2'}
(受控组件)时,该组件不显示 selected 项目。
我必须说我将 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}
/>
}
我尝试在我的 reactjs 应用程序中使用 react-select,但 onChange 事件出现问题。 onChange 应该发送两个参数。第一个应该是 selected 值,但不是 selected 值,整个选项项作为 selected 值传递。
例如
- 我有一系列选项,例如
options=[{ id: '1', name: 'A'},{ id: '2', name:'B'}]
- 我设置了
getOptionValue = (i) => i.id;
和getOptionLabel = (i)=>i.name;
- 当 select 第二项
onChange(value)
作为value
参数传递给第二个选项时 ({id:'2',name:'B'}
) 而不是第二个选项的值 ('2'
).
此行为与大多数输入组件不一致。我希望 onChange
传递项目的值,对于项目本身,我希望另一个事件,如 onItemSelected
或类似的事件。
此外,当我设置 value={'2'}
(受控组件)时,该组件不显示 selected 项目。
我必须说我将 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}
/>
}