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

时间:2019-04-10 14:45:07

标签: react-select

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

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

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的子代必须是字符串。

1 个答案:

答案 0 :(得分:0)

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

您唯一需要的是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

相关问题