在 react-select 2.* 中访问 <Option /> 组件中的 inputValue
Access inputValue in <Option /> component in react-select 2.*
我正在尝试突出显示(下划线或粗体)在我显示的所有选项中输入的文本。这在 react-select 1.* 中非常简单,但我在 2.* 中失败了。尝试访问自定义组件中的 inputValue
时。
此代码片段说明了我在 inputValue
可用时的尝试,如 props
:
import React from 'react'
import match from 'autosuggest-highlight/match/index'
import parse from 'autosuggest-highlight/parse/index'
export default props => {
// Extract matching parts from the inputValue (value typed into text field)
const matches = match(props.label, props.inputValue)
const parts = parse(props.label, matches)
return (
<div>
{parts.map((part, index) => {
return !part.highlight ? (
<span>{part.text}</span>
) : (
<strong>{part.text}</strong>
)
})}
</div>
)
}
如果您使用的是自定义 Option
组件,那么您可以从 props.selectProps
.
中访问 inputValue
const Option = props => {
console.log('props', props);
const { innerProps, innerRef, selectProps, data } = props;
return (
<div ref={innerRef} {...innerProps}>
// generate your highlighted Option from data.label here, using
// selectProps.inputValue
</div>
);
};
// ...
<Select {...otherProps} components={{Option}} />
我正在尝试突出显示(下划线或粗体)在我显示的所有选项中输入的文本。这在 react-select 1.* 中非常简单,但我在 2.* 中失败了。尝试访问自定义组件中的 inputValue
时。
此代码片段说明了我在 inputValue
可用时的尝试,如 props
:
import React from 'react'
import match from 'autosuggest-highlight/match/index'
import parse from 'autosuggest-highlight/parse/index'
export default props => {
// Extract matching parts from the inputValue (value typed into text field)
const matches = match(props.label, props.inputValue)
const parts = parse(props.label, matches)
return (
<div>
{parts.map((part, index) => {
return !part.highlight ? (
<span>{part.text}</span>
) : (
<strong>{part.text}</strong>
)
})}
</div>
)
}
如果您使用的是自定义 Option
组件,那么您可以从 props.selectProps
.
inputValue
const Option = props => {
console.log('props', props);
const { innerProps, innerRef, selectProps, data } = props;
return (
<div ref={innerRef} {...innerProps}>
// generate your highlighted Option from data.label here, using
// selectProps.inputValue
</div>
);
};
// ...
<Select {...otherProps} components={{Option}} />