首页 > 解决方案 > React-select:自定义控件不呈现选择组件

问题描述

对自定义组件使用react-select@next并遵循此处Control的示例不会产生预期的结果。

import TextField from "@material-ui/core/TextField";
import Select from "react-select";

const InputComponent = (props) => {
    return (
        <TextField {...props} />
    );
};

export const MaterialSelect = (props) => {
    const { suggestions, ...other } = props;
    return (
            <Select
                options={suggestions}
                components={{
                    Control: InputComponent,
                }}
                {...other}
            />
    );
};

const suggestions = [
    {
        label: "Test One",
        value: "testOne",
    },
    {
        label: "Test Two",
        value: "testTwo",
    },
];

<MaterialSelect suggestions={suggestions} />

使用 Material-UI TextField 不会打开下拉列表或显示任何装饰。我也尝试过传入而{...props.selectProps}不是没有运气{...props}TextField

我还尝试使用InputPropsprop for单独传递组件,但TextField没有成功。menuIsOpen在我的组件上使用Select会按预期呈现菜单,但是键入TextField不会产生任何结果、没有装饰等。

标签: javascriptreactjsmaterial-designmaterial-uireact-select

解决方案


看来您正在努力使反应选择看起来像材料。假设我可以给你一个例子:

首先你需要实现你的 Options 看起来像材料:

class Option extends React.Component {
  handleClick = event => {
    this.props.selectOption(this.props.data, event);
  };

  render() {
    const { children, isFocused, isSelected, onFocus } = this.props;
    console.log(this.props);
    return (
      <MenuItem
        onFocus={onFocus}
        selected={isFocused}
        onClick={this.handleClick}
        component="div"
        style={{
          fontWeight: isSelected ? 500 : 400
        }}
      >
        {children}
      </MenuItem>
    );
  }
}

那么你需要包装 react-select 并将其作为inputComponent道具放入 material-ui 输入中。

function SelectWrapped(props) {
  const { classes, ...other } = props;

  return (
    <Select
      components={{
        Option: Option,
        DropdownIndicator: ArrowDropDownIcon
      }}
      styles={customStyles}
      isClearable={true}
      {...other}
    />
  );
}

然后将其用作:

 <div className={classes.root}>
    <Input
      fullWidth
      inputComponent={SelectWrapped}
      value={this.state.value}
      onChange={this.handleChange}
      placeholder="Search your values"
      id="react-select-single"
      inputProps={{
        options: testOptions
      }}
    />
  </div>

请指出我在示例中将选项作为 inputProps 传递。

这是一个工作示例:https ://codesandbox.io/s/nk2mkvx92p

请在演示中找到这些customStyles,它们使您的组件具有更多的材料感。

希望这会是你。


推荐阅读