【问题标题】:How to get access to CSS values from a styled component (React)?如何从样式化组件(React)访问 CSS 值?
【发布时间】:2018-08-10 16:48:41
【问题描述】:

我想访问分配给函数中样式化组件的 CSS 值。我该怎么做?

例如:

const Hello = styled.p `
   font-size: 10px;
`;


getFontSize = () => {

}

我想在函数 getFontSize() 中记录组件 Hello 的字体大小。我试过使用 refs 和 InnerRefs 但没有运气。

【问题讨论】:

  • 你能分享你的尝试吗?

标签: javascript css reactjs ref styled-components


【解决方案1】:

您可以在组件上使用innerRef prop 来获取对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)} />;
  }
}

【讨论】:

  • 我试过这个,但我得到“未捕获的类型错误:无法在 'Window' 上执行 'getComputedStyle':参数 1 不是 'Element' 类型。”
  • @Azimi 您是否从我的答案中的示例链接中得到该错误?如果您的意思是在您自己的代码中,则必须确保组件已首先呈现,以便设置 ref
  • 是的,我的组件已渲染,我正在 componentdidmount() 函数中进行调用。我做的几乎和你做的一样。
  • @Azimi 好的。你可能错过了一些微小的细节。例如,您是否将ref 分配给this.ref
  • 我发现了我的问题,感谢您的帮助。再次感谢!
猜你喜欢
  • 2019-01-24
  • 1970-01-01
  • 2016-05-12
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 2021-11-01
  • 2021-01-20
相关资源
最近更新 更多