Javascript 如何从 React 访问样式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35170581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:20:21  来源:igfitidea点击:

How to Access styles from React?

javascriptcssreactjsattributes

提问by mre12345

I am trying to access the width and height styles of a div in React but I have been running into one problem. This is what I got so far:

我试图在 React 中访问 div 的宽度和高度样式,但我遇到了一个问题。这是我到目前为止得到的:

componentDidMount()  {
  console.log(this.refs.container.style);     
}


render()  {
   return (
      <div ref={"container"} className={"container"}></div>  //set reff
   );
}

This works but the output that I get is a CSSStyleDeclaration object and in the all property I can all the CSS selectors for that object but they none of them are set. They are all set to an empty string.

这有效,但我得到的输出是一个 CSSStyleDeclaration 对象,在 all 属性中,我可以设置该对象的所有 CSS 选择器,但它们都没有设置。它们都设置为空字符串。

This is the output of the CSSStyleDecleration is: http://pastebin.com/wXRPxz5p

这是 CSSStyleDecleration 的输出是:http: //pastebin.com/wXRPxz5p

Any help on getting to see the actual styles (event inherrited ones) would be greatly appreciated!

任何有关查看实际样式(事件继承的样式)的帮助将不胜感激!

Thanks!

谢谢!

回答by Vikramaditya

For React v <= 15

对于反应 v <= 15

console.log( ReactDOM.findDOMNode(this.refs.container).style); //React v > 0.14

console.log( React.findDOMNode(this.refs.container).style);//React v <= 0.13.3

EDIT:

编辑:

For getting the specific style value

用于获取特定的样式值

console.log(window.getComputedStyle(ReactDOM.findDOMNode(this.refs.container)).getPropertyValue("border-radius"));// border-radius can be replaced with any other style attributes;

For React v>= 16

对于反应 v>= 16

assign ref using callback style or by using createRef().

使用回调样式或使用 createRef() 分配 ref。

assignRef = element => {
  this.container = element;
}
getStyle = () => {

  const styles = this.container.style;
  console.log(styles);
  // for getting computed styles
  const computed = window.getComputedStyle(this.container).getPropertyValue("border-radius"));// border-radius can be replaced with any other style attributes;
  console.log(computed);
}

回答by flyingace

It's worth noting that while ReactDOM.findDOMNode is usable today, it will be deprecated in the future in place of callback refs.

值得注意的是,虽然 ReactDOM.findDOMNode 今天可用,但将来会弃用它来代替回调引用。

There is a post hereby Dan Abramov which outlines reasons for not using findDOMNode while providing examples of how to replace the use of ReactDOM.findDOMNode with callback refs.

Dan Abramov在这里发表一篇文章,其中概述了不使用 findDOMNode 的原因,同时提供了如何用回调引用替换 ReactDOM.findDOMNode 的示例。

Since I've seen SO users get upset when only a link was included in an answer, so I will pass along one of the examples Dan has kindly provided:

由于我已经看到 SO 用户在答案中只包含一个链接时会感到不安,因此我将传递 Dan 提供的示例之一:

findDOMNode(stringDOMRef)

findDOMNode(stringDOMRef)

**Before:**

class MyComponent extends Component {
  componentDidMount() {
    findDOMNode(this.refs.something).scrollIntoView();
  }

  render() {
    return (
      <div>
        <div ref='something' />
      </div>
    )
  }
}
**After:**

class MyComponent extends Component {
  componentDidMount() {
    this.something.scrollIntoView();
  }

  render() {
    return (
      <div>
        <div ref={node => this.something = node} />
      </div>
    )
  }
}

回答by mtomic

You should use ReactDOM.findDOMNodemethod and work from there. Here's the code that does what you need.

您应该使用ReactDOM.findDOMNode方法并从那里开始工作。这是执行您需要的代码。

var Hello = React.createClass({

componentDidMount: function() {
  var elem = ReactDOM.findDOMNode(this.refs.container);
  console.log(elem.offsetWidth, elem.offsetHeight);    
},

render: function() {
   return (
      <div ref={"container"} className={"container"}>
        Hello world
      </div>
   );
}
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

jsFiddle

js小提琴

回答by Purkhalo Alex

Here is an example of computing the CSS property value via React Refsand .getComputedStylemethod:

这是通过React Refs.getComputedStyle方法计算 CSS 属性值的示例:

class App extends React.Component {
    constructor(props) {
        super(props)
        this.divRef = React.createRef()
    }

    componentDidMount() {
        const styles = getComputedStyle(this.divRef.current)

        console.log(styles.color) // rgb(0, 0, 0)
        console.log(styles.width) // 976px
    }

    render() {
        return <div ref={this.divRef}>Some Text</div>
    }
}

回答by David Guan

You already get the style, the reason why CSSStyleDeclaration object's props have so much empty string value is it's link to the inner style.

您已经获得了样式,CSSStyleDeclaration 对象的 props 具有如此多空字符串值的原因是它与内部样式的链接。

See what will happen if you make change like below:

看看如果您进行如下更改会发生什么:

<div ref={"container"} className={"container"} style={{ width: 100 }}></div>

<div ref={"container"} className={"container"} style={{ width: 100 }}></div>