gpt4 book ai didi

javascript - React-select:自定义控件不呈现选择组件

转载 作者:行者123 更新时间:2023-11-30 09:21:45 25 4
gpt4 key购买 nike

使用 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} />

使用 Material-UI TextField 不会打开下拉菜单或显示任何装饰。我还尝试将 {...props.selectProps} 而不是 {...props} 传递给 TextField 但没有成功

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

最佳答案

看来您正在努力使 react select 看起来像 Material 。假设我可以给你举个例子:

首先你需要实现你的选项看起来像 Material :

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 prop 放在 material-ui Input 中。

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,它们可以让您的组件更有质感。

希望这会是你。

关于javascript - React-select:自定义控件不呈现选择组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51216547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com