javascript - 如何从样式化组件 (React) 访问 CSS 值?

标签 javascript css reactjs ref styled-components

我想在函数中访问我分配给样式化组件的 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)} />;
  }
}

关于javascript - 如何从样式化组件 (React) 访问 CSS 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51790873/

相关文章:

javascript - Bootstrap-datepicker 不显示

css - 菜单在 IE7 中随机出现/消失

javascript - 如何为包括视频/div/iframe 在内的所有元素翻转 X?

reactjs - 类型 'background' 上不存在属性 '{}' - React Router 模态

javascript - 尝试使用 Context API 时看到 "render is not a function"

javascript - 表单提交引导后禁用按钮 AngularJs

javascript - 运行条形码扫描仪时如何停止提交表单

Javascript定义变量符号问题

CSS 媒体查询否定

javascript - 查看按钮点击 react 中的日期