简体   繁体   English

React.js:如何从已安装的CSS类属性 <div> ?

[英]Reactjs: How to get a css-class attribute from a mounted <div>?

Lets say I have a react DOM element like this one: 可以说我有一个类似的DOM元素:

render () {
  ...
  return (
    <div className = "widePaddingRight" style = {{width: "100px"}}
      ref = "pickMe"
    >
      ...
    </div>
  )
}

CSS: CSS:

.widePaddingRight{
  paddingRight: 20px
}

If I access this element later and try to get its width like that: 如果以后再访问此元素,然后尝试像这样获取其宽度:

componentDidMount () {
  var elem = this.refs.pickMe.getDOMNode().getBoundingClientRect()
  console.log(elem.width)
}

I get 120 in my console. 我的控制台中得到120 My expected result was 100 . 我的预期结果是100 Since I have to calculate with the original width I have to get the padding-attributes of the element. 由于我必须使用原始宽度进行计算,因此必须获取元素的填充属性。

Question: How can I get the paddingRight attribute of my component in my react-class? 问题:如何在我的paddingRight -Class中获取组件的paddingRight属性?

Update With the input of @Mike 'Pomax' Kamermans I was able to solve the underlying problem (thank you for that): Just add box-sizing: border-box to the CSS. 更新与@Mike“Pomax” Kamermans的输入我能够解决根本问题(感谢你):只需添加box-sizing: border-box的CSS。 Now getBoundingClientRect() gives 100 instead of 120 . 现在, getBoundingClientRect()给出100而不是120

I still dont know how to get a css class-attribute from a mounted div - any suggestions? 我仍然不知道如何从已挂载的div获取CSS类属性-有什么建议吗?

您需要window.getComputedStyle

const style = window.getComputedStyle(React.findDOMNode(this.refs.pickMe));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM