javascript - 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>
}
}
解决方案
首先,您可以阅读有关Refs 和 DOM 的信息。
然后,您可以尝试将您的子元素与每个元素与另一个元素进行映射,并在那里传递一个ref
via 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
功能。
推荐阅读
- powerbi - Power Query - 日期到儒略日期
- java - 使用 Selenium 和 Java 的线程“主”java.util.NoSuchElementException 中的异常错误
- pascal - 编程 PascalABC。为什么“输出”没有任何文字?
- python - 通过 np.concatenate python 连接值
- api - SuiteCRM API v8:密码授予的登录/身份验证不起作用
- node.js - 如何使用 Node.js 在 Sequelize 6 中实现实例方法
- python - Python - 每行中匹配值的计数频率
- sql - SQL 连接查询到库
- python - Plotly:用两个非线性相关的 x 轴绘制一条轨迹
- excel - 基于映射表进行比较