使用material-ui样式化react-select v2 - 替换输入组件

6

我在将react-select v2的Input组件替换为来自Material UI的Input组件时遇到了问题。

我已经在下面的codesandbox中尝试了一些,但无法在输入时调用过滤功能?

https://codesandbox.io/s/jjjwoj3yz9

另外,如果有关于选项替换实现的任何反馈将不胜感激。我是否正确地获取了所点击选项的文本,并从我的选项列表中搜索Option对象以传递给selectOption函数?

非常感谢, Eric

1个回答

9

V1

请参考此处的文档:https://material-ui.com/demos/autocomplete/

该文档详细说明了如何在 material-ui 中使用 react-select。

以下是一个可工作的示例,可供您参考:https://codesandbox.io/s/p9jpl9l827

正如您所见,material-ui 的 Input 组件可以将 react-select 作为 inputComponent

V2

这个方法与之前的方法几乎相同:

实现 Input 组件:

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

然后SelectWrapped组件的实现应该是:

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

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

我重写了组件Option和DropdownIndicator,使其更符合Material风格,并添加了customStyles

const customStyles = {
  control: () => ({
    display: "flex",
    alignItems: "center",
    border: 0,
    height: "auto",
    background: "transparent",
    "&:hover": {
      boxShadow: "none"
    }
  }),
  menu: () => ({
    backgroundColor: "white",
    boxShadow: "1px 2px 6px #888888", // should be changed as material-ui
    position: "absolute",
    left: 0,
    top: `calc(100% + 1px)`,
    width: "100%",
    zIndex: 2,
    maxHeight: ITEM_HEIGHT * 4.5
  }),
  menuList: () => ({
    maxHeight: ITEM_HEIGHT * 4.5,
    overflowY: "auto"
  })
};

选择项(Option):
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>
    );
  }
}

请从这里查看示例:https://codesandbox.io/s/7k82j5j1qx 参考 React Select 文档,如果需要可以添加更多更改。
希望这些内容能对您有所帮助。

1
嗨@gluttony,感谢您的回复。但是,我正在寻找使用react-select版本2(即我的codesandbox示例中的2.0.0-beta6)的解决方案。我已经看过了来自material-ui.com/demos/autocomplete的文档,不幸的是,它是针对react-select的第1个版本。谢谢。 - drivenj17
2
@Nadun我相信现在代码沙盒示例已经过时了。 - Sachin Kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接