【问题标题】:How to Access styles from React?如何从 React 访问样式?
【发布时间】:2016-05-12 06:26:11
【问题描述】:

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

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


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

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

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

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

谢谢!

【问题讨论】:

  • 尝试改用window.getComputedStyle(this.refs.container)
  • 天哪!效果很好......这是常用的吗?因为我以前从未在 React Docs 上见过它
  • 它不是 React 功能,在旧 IE (
  • 我试过这个并得到Cannot read property 'refs' of undefined

标签: javascript css reactjs attributes


【解决方案1】:

对于 React v

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

编辑:

用于获取具体的样式值

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

对于反应 v>= 16

使用回调样式或使用 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);
}

【讨论】:

  • React.findDOMNode deprecated?
  • 是的,React.findDOMNode 在反应 0.13.3 之前一直存在。现在使用 ReactDOM 进行所有与 DOM 相关的操作。
  • 我认为 Dan Abramov 在the Github issue I linked 中所说的是该方法将被弃用,无论是来自React.findDOMNode 还是ReactDOM.findDOMNode。来自the documentation on ReactDOM.findDOMNode:“findDOMNode 是一个用于访问底层 DOM 节点的逃生舱口。在大多数情况下,不鼓励使用此逃生舱口,因为它会穿透组件抽象。” Dan 建议改用ref
  • 添加关于弃用 findDOMNode 的信息:it doesn't work with the Jest test renderer (but refs do)(Dan Abramov:“没有计划在测试渲染器中支持 findDOMNode(),因为它应该与 React DOM 无关,并且存在无法以将来不会中断的方式实现它。”)
  • findDOMNode 已弃用。我已经更新了@Cyber​​Junkie 的答案。
【解决方案2】:

这是一个通过 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>
    }
}

【讨论】:

    【解决方案3】:

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

    Dan Abramov 有一篇 here 的帖子概述了不使用 findDOMNode 的原因,同时提供了如何用回调引用替换 ReactDOM.findDOMNode 的示例。

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

    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>
        )
      }
    }
    

    【讨论】:

    • 糟糕!我刚刚注意到,在接受的答案下方的 cmets 中已经提到了这一点。 :P
    • 不管怎样,如果您正在使用功能组件和 useRef() 钩子,那么现在使用 refs 会更加容易! (reactjs.org/docs/hooks-reference.html#useref)
    【解决方案4】:

    您应该使用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

    【讨论】:

      【解决方案5】:

      如果是函数组件,请使用 useRef Hook:

        const _optionsButton = useRef(null);
        const _onSelectText = (event) => {
          if (true) {
            _optionsButton.current.style["display"] = "block";
          } else {
            _optionsButton.current.style["display"] = "none";
          }
          console.log(_optionsButton.current.style); //all styles applied to element
        };
      

      为组件添加 ref 属性

      <IconButton
                  style={{
                    color: "rgba(0, 0, 0, 0.54)",
                    fill: "rgba(0, 0, 0, 0.54)",
                    border: "1px solid rgba(0, 0, 0, 0.54)",
                    position: "absolute",
                    display: "none",
                  }}
                  color="primary"
                  component="span"
                  onClick={() => {}}
                  ref={_optionsButton} //this
                >
                  Check
       </IconButton>
      

      谢谢

      【讨论】:

        【解决方案6】:

        你已经得到了样式,CSSStyleDeclaration 对象的 props 有这么多空字符串值的原因是它与内部样式的链接。

        看看如果你做出如下改变会发生什么:

        &lt;div ref={"container"} className={"container"} style={{ width: 100 }}&gt;&lt;/div&gt;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-02-06
          • 2023-03-21
          • 2015-11-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多