使用React.findDOMNodev0.13.0中引入的方法,我可以通过映射到来获取传递给父级的每个子组件的DOM节点this.props.children。
React.findDOMNode
this.props.children
但是,如果某些子项恰好是React Elements而不是Components(例如,其中一个子项是<div>通过JSX创建的),则React会引发不变的违规错误。
<div>
挂载后,是否有一种方法可以获取每个子级的正确DOM节点,而不管该子级是什么类?
this.props.children 应该是一个ReactElement或一个ReactElement数组,但不能是组件。
要获取子元素的DOM节点,您需要对其进行克隆并为其分配新的引用。
render() { return ( <div> {React.Children.map(this.props.children, (element, idx) => { return React.cloneElement(element, { ref: idx }); })} </div> ); }
然后,您可以通过访问子组件this.refs[childIdx],并通过检索其DOM节点ReactDOM.findDOMNode(this.refs[childIdx])。
this.refs[childIdx]
ReactDOM.findDOMNode(this.refs[childIdx])