css - 有没有办法在保持大部分原始风格的同时对反应选择进行风格化?
问题描述
我正在使用https://react-select.com/home#getting-started并且我正在尝试创建尽可能接近此的内容:
我编码的原始选择样式(没有选择库中的customStyles函数)给了我这样的东西:
但是一旦我开始添加样式(选择库中的customStyles函数),如下所示:
import { useEffect, useState } from 'react';
// styled components
import styled from 'styled-components';
// icons
import { IoIosArrowDown } from 'react-icons/io';
// select input
import Select from 'react-select';
const ContextItem = ({ text, options }) => {
const [treeNodeNames, setTreeNodeNames] = useState();
// THIS IS FROM THE LIBRARY
const customStyles = {
option: (provided, state) => ({
...provided,
// borderBottom: '1px dotted pink',
color: state.isSelected ? 'white' : 'black',
}),
control: () => ({
// none of react-select's styles are passed to <Control />
width: 200,
}),
singleValue: (provided, state) => {
const opacity = state.isDisabled ? 0.5 : 1;
const transition = 'opacity 300ms';
return { ...provided, opacity, transition };
},
};
useEffect(() => {
if (options) {
const treeNodes = options.data.findTreeNodesByTree.map((element) => {
return {value: element.name, label: element.name };
});
setTreeNodeNames(treeNodes);
}
}, [options]);
return (
<ContextContainer>
<ContextTitle>
<p> {text}</p>
</ContextTitle>
{treeNodeNames && (
<SearchInput>
<Select options={treeNodeNames} styles={customStyles} />
</SearchInput>
)}
</ContextContainer>
);
};
// STYLES
const ContextContainer = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
`;
const ContextTitle = styled.div`
display: flex;
width: 30%;
align-items: center;
justify-content: space-between;
`;
const SearchInput = styled.div`
width: 60%;
padding: 5px;
outline: black;
`;
export default ContextItem;
我得到这样的东西:
所以问题是:如何在不破坏所有内容的情况下使用 select中的customStyles实现第一张照片中显示的预期结果?有没有办法将原始反应选择的样式传递给并相应地修改它们。最后我只需要:
- 选择选项周围没有边框
- 选择选项向右移动
- 相同的颜色
- 但是选择或悬停时的背景不同
- 并且单击所选输入字段时没有更改边框颜色
我希望有道理,如果问题不清楚,请告诉我:) 我感谢任何形式的帮助和线索。
解决方案
这个react-select组件由多个较小的部分组成。
您在正确的轨道上应用自定义样式。这是您可以自定义的 react-select 的各个部分的列表。语法:
const customStyles = {
option: (provided, state) => ({
...provided,
color: state.isSelected ? 'red' : 'blue',
// rest of styling
})
}
例如,如果您想更改没有可用选项的文本,您将设置noOptionsMessage的样式。
其他需要注意的事项:
- 要访问类似于选项
:hover
组件的伪类,CSS-in-JS 使用以下语法:."&:hover": {...}
- 有关如何在此处检查组件的伪状态和设置样式的更多详细信息。
这是一个代码框,它的 react-select 样式接近您的第一张图片。
推荐阅读
- deep-linking - 无法从 Skype 应用程序打开我的应用程序,但可以在 Messenger 上打开它
- html - 做`context.canvas.width`和`canvas.width`有什么区别?
- mysql - 如何在 SELECT 语句中使用 HAVING 子句?
- python - 如何将数据库包含在 .py 到 .exe 中?
- powershell - 将 PnPFile 从站点移动到个人 onedrive 站点
- javascript - 无法使用带有 Fetch API 获取请求的 foreach 循环从 API 获取多个数据
- javascript - 从 expo 环境调用后 Firestore 返回元数据
- swiftui - SwiftUI 按钮的 Aura 动画
- python - 如何使用beautifulsoup python web scrape在不使用表单的情况下获取浏览器中给出的输入标签值
- c++ - 在 C++ 文件主体中分配内存和设置值到引用变量的问题(不在函数中)