代码之家  ›  专栏  ›  技术社区  ›  Naji

反应选择:自定义控件不呈现选择组件

  •  1
  • Naji  · 技术社区  · 6 年前

    使用 react-select@next 并以身作则 here 用于自定义 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} />
    

    使用材质ui文本字段不会打开下拉列表或显示任何装饰。我也试过进来 {...props.selectProps} 而不是 {...props} TextField 运气不好

    我还尝试使用 InputProps 支柱 文本字段 没有运气。使用 menuIsOpen 关于我的 Select 组件按预期呈现菜单,但键入 文本字段 不产生结果,不产生装饰等。

    1 回复  |  直到 6 年前
        1
  •  4
  •   Nadun    6 年前

    似乎你在努力让react select看起来像是材料。 假设我可以给你举个例子:

    首先,你需要实现你的选择看起来像材料:

    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并将其作为 输入组件 物料界面输入中的道具。

    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

    请找到这些 自定义样式 在演示中,使您的组件具有更多的材质感觉。

    希望这会是你。