在react-select 2. *的<option>组件中访问inputValue

时间:2018-11-01 09:50:25

标签: reactjs react-select

我试图突出显示(加下划线或加粗)在所有显示的选项中输入的文本。这在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>
    )
}

1 个答案:

答案 0 :(得分:1)

如果您使用的是自定义Option组件,则可以从inputValue内部访问props.selectProps

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}} />