react-select 将自定义组件渲染为 SingleValue

标签 react-select

我需要使用 react-select 和 typescript 在所选值之前显示一个图标。

这是我到目前为止尝试过的:

SingleValue: React.SFC<SingleValueProps<OptionType>> = ({ children, ...props }) => (
    <components.SingleValue {...props}>
      <i className={`fal fa-${this.props.icon} has-text-grey-light`} /> {children}
    </components.SingleValue>
  )

主要问题是类型定义要求传递给 components.SingleValue 的子项必须是字符串。

最佳答案

您不必使用标准组件。您可以轻松创建自定义样式,但仍保留其所需的样式。

您唯一需要的是 emotion 来获取 SingleValue 组件使用的样式。

/**
 * This Example uses the `FontAwesome` React library.
**/

const options = [
  { label: "Value A", value: "a", icon: faCoffee },
  { label: "Value B", value: "b", icon: faCar },
  { label: "Value C", value: "c", icon: faMobile },
  { label: "Value D", value: "d", icon: faCircle },
  { label: "Value E", value: "e", icon: faSquare }
];

const SingleValue = ({
  cx,
  getStyles,
  selectProps,
  data,
  isDisabled,
  className,
  ...props
}) => {
  console.log(props);
  return (
    <div
      className={cx(
        emotionCss(getStyles("singleValue", props)),
        {
          "single-value": true,
          "single-value--is-disabled": isDisabled
        },
        className
      )}
    >
      <FontAwesomeIcon icon={data.icon} style={{ marginRight: 10 }} />
      <div>{selectProps.getOptionLabel(data)}</div>
    </div>
  );
};

export default class MySelect extends Component {
  render() {
    return (
      <Select
        options={options}
        components={{ SingleValue }}
        styles={{
          singleValue: (provided, state) => ({
            ...provided,
            display: "flex", // To keep icon and label aligned
            alignItems: "center"
          })
        }}
      />
    );
  }
}

Working example

关于react-select 将自定义组件渲染为 SingleValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55615451/

相关文章:

javascript - 如何摆脱或删除 react 选择中的微调器/箭头?

reactjs - 如何使用react-testing-library触发react-select组件上的更改事件?

reactjs - 使用 Formik 与 Yup 和 React-select 进行验证

css - React-selectize 无法加载 css

reactjs - 如何为react-select异步设置defaultValue并且在v2.0.0的onBlur时不重置?

javascript - 如何更改输入容器的样式

css - React-Select 移除焦点边框

javascript - 无法获取输入选择表单的初始值

javascript - 如何使用 react-select 和 react-bootstrap 来获取值

html - react-select inputProps 未应用于 AsyncSelect