Javascript 如何从样式化组件(React)访问CSS值?
我想访问我分配给函数中一个样式化组件的CSS值。我该怎么做 例如:Javascript 如何从样式化组件(React)访问CSS值?,javascript,css,reactjs,ref,styled-components,Javascript,Css,Reactjs,Ref,Styled Components,我想访问我分配给函数中一个样式化组件的CSS值。我该怎么做 例如: const Hello = styled.p ` font-size: 10px; `; getFontSize = () => { } 我想在函数getFontSize()中记录组件Hello的字体大小。我尝试过使用refs和InnerRefs,但没有成功 您可以在组件上使用innerRef属性获取对DOM节点的引用,然后在节点上使用以获取字体大小 示例 const Hello = styled.input
const Hello = styled.p `
font-size: 10px;
`;
getFontSize = () => {
}
我想在函数getFontSize()中记录组件Hello的字体大小。我尝试过使用refs和InnerRefs,但没有成功 您可以在组件上使用
innerRef
属性获取对DOM节点的引用,然后在节点上使用以获取字体大小
示例
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)} />;
}
}
const Hello=styled.input`
填充:0.5em;
边缘:0.5em;
颜色:淡紫罗兰色;
背景:番木瓜;
边界:无;
边界半径:3px;
字体大小:10px;
`;
类形式扩展了React.Component{
ref=null;
componentDidMount(){
这个.getFontSize();
}
getFontSize=()=>{
console.log(
getComputedStyle(this.ref,null).getPropertyValue(“字体大小”)
);
};
render(){
返回(this.ref=ref)}/>;
}
}
你能分享你的尝试吗?我尝试了这个,但我得到了“未捕获的TypeError:无法在“窗口”上执行“getComputedStyle”:参数1不是“元素”类型。@Azimi你从我答案中的示例链接中得到了这个错误吗?如果您的意思是在您自己的代码中,则必须确保组件已首先呈现,以便设置ref
。是的,我的组件已呈现,我正在componentdidmount()函数中进行调用。“我做的和你做的差不多。”阿齐米:好的。你可能错过了一些小细节。例如,您是否将ref
分配给this.ref
?我解决了我的问题,感谢您的帮助。再次感谢!