我目前使用的是带有React的styled-components 5.0.1。https://styled-components.com/
对于上下文,我的目标是在一个模式中聚焦陷阱。
我的问题是类名是从styled-components随机生成的,所以我不能用querySelector访问这些DOM节点。我的另一个问题是,我不能使用React引用转发,因为我必须在组件树之间进行大量的引用转发。
有没有办法访问从样式化组件生成的类名?如果是这样的话,我就可以使用querySelector,通过querySelector访问DOM节点,按照通常的方式进行焦点捕获。
发布于 2021-02-02 04:20:01
我能够通过使用data-属性访问DOM节点来解决这个问题。
例如,
const myComponent = styled.div`
// ...styles here
`;
const foo = () => (
<myComponent
data-foo-bar="foobar"
/>
);
console.log(document.querySelector('[data-a11y-id="HeaderNavBar-SearchButton"]');
// returns the DOM element for myComponent发布于 2021-01-15 04:56:57
首先,您的组件应该能够处理传入的css:
import styled from "styled-components";
const Box = styled.div`
color: red;
${props => props.addCSS}
`;
const DatePicker = () => <Box>DatePicker</Box>;其次,声明css样式。
import { css } from "styled-components";
const myCSS = css`
font-size: 60px;
`;最后,将其向下传递给子组件。
<DatePicker addCSS={myCSS} />https://stackoverflow.com/questions/65726573
复制相似问题