选择选项时将值作为字符串发送 [英] send the value as string when selecting the option
问题描述
我将 react-select 用于自动完成和选项相关字段.当我选择该选项时,它会将整个选项对象作为 {value: 'abc', label: 'ABC'}
传递,但我只想将值作为字符串而不是对象传递.因此,我使用了 getOptionValue 但它没有按预期工作.
I am using react-select for autocomplete and option related field. When i select the option it passes whole that option object as {value: 'abc', label: 'ABC'}
but i wanted only to pass the value as a string not the object. Thus, i used getOptionValue but it is not working as expected.
这就是我所做的
<Field
name='status'
component={SearchableText}
placeholder="Search..."
options={status}
styles={styles}
getOptionLabel={option => option.label}
getOptionValue={option => option.value}
/>
我同时使用了 getOptionLabel
和 getOptionValue
,但仍然以对象形式传递所选选项,而不仅仅是将值作为字符串传递.
I have used both getOptionLabel
and getOptionValue
but is still passing the selected option in object form instead of just the value as string.
期待一个
status: 'active'
当前行为
status: { value: 'active', label: 'Active'}
推荐答案
我在 react-select 的文档中找不到 getOptionValue
,但您始终可以围绕 react-select 创建一个适配器.即创建您自己的 Select 组件,该组件在内部使用 react-select 的 Select 组件.这样做之后,就可以创建您自己的 getOptionValue
.您可以使用它来确保该值是一个字符串.
I couldn't find getOptionValue
in the docs for react-select, but you could always create an adapter around react-select. i.e. create your own Select component that uses react-select's Select component internally. After doing this it becomes possible to create your own getOptionValue
. You can use this to make sure the value is a string.
import React from "react";
import Select from "react-select";
class MySelect extends React.Component {
getSelectValue() {
return this.props.options.find(
option => this.props.getOptionValue(option) === this.props.input.value
);
}
render() {
console.log("value", this.props.input.value);
return (
<Select
value={this.getSelectValue()}
onChange={option => {
this.props.input.onChange(this.props.getOptionValue(option));
}}
options={this.props.options}
/>
);
}
}
MySelect.defaultProps = {
getOptionValue: v => v
};
const MyForm = reduxForm({ form: "MyForm" })(
class extends React.PureComponent {
render() {
return (
<Field
name="myCoolSelect"
component={MySelect}
options={[
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
]}
getOptionValue={option => option.value}
/>
);
}
}
);
以上是如何实现此功能的基本示例.您可能希望传递其他输入或元道具以利用其他 redux-form 功能.例如onBlur
、onFocus
等.你可以在这里看到它的实际效果:https://codesandbox.io/s/6wykjnv32n
The above is a basic example of how to get this working. You may want to pass other input or meta props to take advantage of other redux-form features. e.g. onBlur
, onFocus
, etc. You can see it in action here: https://codesandbox.io/s/6wykjnv32n
这篇关于选择选项时将值作为字符串发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!