首页 > 解决方案 > React 获取在 props 中传递的子元素的原生元素或高度和宽度

问题描述

我如何获得原生 html 元素或获得作为子元素传递给道具的元素的边界?

给定下一个组件:

class SomeComp extends Component {
    componentDidMount() {
       this.props.children.forEach(child => {
           // I need the native element to get the offsetTop and the .getBoundingClientRect() func of html 
       })
    }
    render() {
        <div>
         {this.props.children}
        </div>
    }
}

标签: javascriptreactjs

解决方案


首先,您可以阅读有关Refs 和 DOM 的信息。

然后,您可以尝试将您的子元素与每个元素与另一个元素进行映射,并在那里传递一个refvia prop 的实例。之后,您可以DOM通过该 ref 实例访问包装器的特定元素。

请参见下面的示例(示例自 以来有效React 16.3):

解决方案已更新以停止添加额外的 div 作为子级的包装器。

class App extends React.Component {
  constructor(props) {
    super(props);
    
    this.refsArray = [];
  }
  
  componentDidMount() {
    this.refsArray.forEach(ref => {
      console.log(ref.current.offsetTop);
    })
  }

  render() {
    return ( 
      <div>
        {React.Children.map(this.props.children, (child, index) => {
          const ref = React.createRef();
          this.refsArray.push(ref); 

          return React.cloneElement(child, {ref, key: index});
        })}
      </div>
    );
  }
}

ReactDOM.render((
  <App>
    <div>This</div>
    <div>is</div>
    <div>my</div>
    <div>test</div>
  </App>
), document.getElementById('root'));
<div id="root"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.1/umd/react-dom.production.min.js"></script>

实现DOM特定已安装组件的特定元素的另一种方法是通过ReactDOM.findDOMNode(component)(参见官方文档)。但是不建议使用这种方法来支持使用refs功能。


推荐阅读