如何从样式化组件 (React) 访问 CSS 值?
How to get access to CSS values from a styled component (React)?
我想访问我在函数中分配给样式化组件的 CSS 值。我该怎么做?
例如:
const Hello = styled.p `
font-size: 10px;
`;
getFontSize = () => {
}
我想在函数getFontSize() 中记录组件Hello 的字体大小。我试过使用 refs 和 InnerRefs 但没有成功。
您可以在组件上使用 innerRef
属性来获取对 DOM 节点的引用,然后在节点上使用 window.getComputedStyle
来获取 font-size
.
例子
const Hello = styled.input`
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
font-size: 10px;
`;
class Form extends React.Component {
ref = null;
componentDidMount() {
this.getFontSize();
}
getFontSize = () => {
console.log(
window.getComputedStyle(this.ref, null).getPropertyValue("font-size")
);
};
render() {
return <Hello innerRef={ref => (this.ref = ref)} />;
}
}
我想访问我在函数中分配给样式化组件的 CSS 值。我该怎么做?
例如:
const Hello = styled.p `
font-size: 10px;
`;
getFontSize = () => {
}
我想在函数getFontSize() 中记录组件Hello 的字体大小。我试过使用 refs 和 InnerRefs 但没有成功。
您可以在组件上使用 innerRef
属性来获取对 DOM 节点的引用,然后在节点上使用 window.getComputedStyle
来获取 font-size
.
例子
const Hello = styled.input`
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
font-size: 10px;
`;
class Form extends React.Component {
ref = null;
componentDidMount() {
this.getFontSize();
}
getFontSize = () => {
console.log(
window.getComputedStyle(this.ref, null).getPropertyValue("font-size")
);
};
render() {
return <Hello innerRef={ref => (this.ref = ref)} />;
}
}