reactjs - React-Select 失去自定义组件“ValueContainer”的焦点
问题描述
我们有一个用例,我们必须为多选下拉列表呈现多个不同版本的值容器,具体取决于选择了多少选项。下面的代码片段显示了其中一种情况。这个的另一个版本呈现一个<SingleValue />
而不是占位符。
<ValueContainer {...props}>
<Placeholder {...props}>
{!props.selectProps.inputValue && `${length} selected`}
</Placeholder>
{children[1]}
</ValueContainer>
这似乎运作良好,但是在选择其中一个选项时我们失去了键盘导航。我是否忘记传递某些道具或裁判?
可以在此处找到自定义 ValueContainer 的删除键盘导航示例:https ://codesandbox.io/s/rjvkzk1nn?from-embed
解决方案
键盘不再工作,因为您错过了Input
打开Menu
.
ValueContainer
没有选择值时有两个对象:
Placeholder
Input
当您选择一个(或多个)值时,它会更改为:
SingleValue
或者MultiValue
Input
在您之前的示例中,您正在删除这两个。
要保留键盘功能,您需要保留Input
组件。以下代码是您的代码和期望并保留Input
组件的组合:
const ValueContainer = ({ children, ...props }) => {
const { getValue, hasValue } = props;
const newChildren = _.cloneDeep(children);
const nbValues = getValue().length;
newChildren[0] = `${nbValues} items selected`;
if (!hasValue) {
return (
<components.ValueContainer {...props}>
{children}
</components.ValueContainer>
);
}
return (
<components.ValueContainer {...props}>
{newChildren}
</components.ValueContainer>
);
};
const options = [
{ label: "label 1", value: 1 },
{ label: "label 2", value: 2 },
{ label: "label 3", value: 3 },
{ label: "label 4", value: 4 }
];
function App() {
const components = { ValueContainer };
return <Select isMulti components={components} options={options} />;
}
推荐阅读
- php - 在 PHP 中使用 &$variable 时内存中会发生什么?
- spring-boot - 无法使用 AbstractReactiveElasticsearchConfiguration 将数据写入 ElasticSearch
- r - 通过索引选择 data.table 列的问题
- c++ - OpenGL - 在一个函数中加载多个纹理
- java - CBC 和 CFB 模式下的 Java AES 未正确加密?四不尊重?
- javascript - 无论如何要从中删除波斯/阿拉伯数字或者在手机里?
- python - 尝试以 FASTA 格式读取文件,然后以 Genbank 格式写入另一个文件
- github - 如何在 Github Repo 上更改“通过上传添加文件”?
- python - 将数据转换为与 CSV 相同格式的 JSON
- python - 在python的For循环中获取索引