javascript - 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
我还尝试使用InputProps
prop for单独传递组件,但TextField
没有成功。menuIsOpen
在我的组件上使用Select
会按预期呈现菜单,但是键入TextField
不会产生任何结果、没有装饰等。
解决方案
看来您正在努力使反应选择看起来像材料。假设我可以给你一个例子:
首先你需要实现你的 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,它们使您的组件具有更多的材料感。
希望这会是你。
推荐阅读
- visual-studio-2019 - InvalidProjectFileException:升级到 VS2019 后来自 Microsoft.Build.Evaluation.Project 的“未找到 SDK 'Microsoft.NET.Sdk.Web'”
- javascript - javascript array.Join 连续 srings 值到新数组中
- python - 您如何运行在视频结束时关闭的可读视频文件
- cups - 如何设置网络打印杯
- python-3.x - 从 tkinter 组合框返回的项目是
而不是 str 本身 - express - 什么会使expressjs 503?
- python - 如何读取 gekko 错误代码(例如位置:5、v3 等)
- debian - 如何更改 debian 软件的手册页部分?
- java - 谁能解释为什么会发生此错误?(a==2) 在这里已经是真的
- django - Django - 使用在 url 中传递的参数预填充 ModelForm