繁体   English   中英

反应-在不破坏封装的情况下访问DOM

[英]react - accessing DOM without breaking encapsulation

是否有一种规范的方法可以进行以下操作而不破坏封装?

import React, { Component, PropTypes } from 'react';

class Dashboard extends Component {
    constructor(props, context) {
        super(props, context);

        this.setRef = ::this.setRef;
    }
    componentDidMount() {
        const node = ReactDOM.findDOMNode(this.someRef);
        const newHeight = window.innerHeight - node.offsetTop - 30;
        node.style.maxHeight = `${newHeight}px`;
    }

    render() {
        return (
            <div id="some-element-id" ref={this.setRef}>
            </div>
        );
    }

    setRef(ref) {
        this.someRef= ref;
    }
}

ReactDOM.findDOMNode似乎是解决此问题的建议方法,但是这仍然会破坏封装,并且文档在这个程度上有很大的ReactDOM.findDOMNode

尽管从一般意义上说,这在技术上“破坏了封装”,但是如果没有其他方法(在这种情况下没有),那么使用findDOMNode是您唯一的选择,这是正确的选择。

如果发现自己反复使用它,则应创建一个包装器组件以封装该行为。

您应该使用组件“状态”来设置react元素的样式属性 ,因此您仅访问“真实” DOM节点以计算高度,然后更新状态,重新渲染该组件。 现在,react组件具有与真实DOM节点相同的信息,因此它不应破坏封装。

使用vanilla JS提供一个示例:

var Component = React.createClass({
    getInitialState: function(){
    return {
        style: {},
    }
  },
  componentDidMount: function(){
    var node = ReactDOM.findDOMNode(this);
    var newHeight = window.innerHeight - node.offsetTop - 30;
    this.setState({style: {backgroundColor: '#bbb', height: newHeight.toString() + 'px' }});
  },
  render: function(){
    return React.createElement('div', {style: this.state.style}, 'Height: ' + this.state.style.height);
  },
});

您可以看到它在这个小提琴中运行。

暂无
暂无

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

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