有没有办法获得 React 组件子项的宽度。我有一个包装器组件,因为缺少名称 Container 并且我从 Component1 向它添加了 div 类型的子项。见下面的例子。我想知道是否有办法在挂载时获取 Container 中每个 div 子项的宽度。
更新说明: 我尝试获取容器子项宽度的原因是我可以根据子项总数动态设置容器宽度。通过将容器宽度设置为儿童宽度的数量,然后我可以允许一些我想做的水平滚动效果。
组件 1
export default class Component1 extends Component{
render(){
return(
<Container>
<div className="large-box"/>
<div className="large-box-dark"/>
</Container>
)
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的容器组件。
export default class Container extends Component{
componentDidMount(){
this.props.children.forEach(( el ) => {
// get each child's width
console.log("el =", el);
});
}
render() {
return (
<div className="scroller" ref={(scroller) => { this.scroller = scroller }}>
{this.props.children}
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用refs。尽管除非没有其他办法,否则您应该避免接触 DOM。但我们开始了。
给你的子组件一个 ref ,它是 React 提供的逃生舱口来访问 DOM(在使用其他方法之前警告)。
子组件
class ChildComp extends Component {
getWidth = () => {
//Access the node here and get the width
return this.childNode.offsetWidth(); //or clientWidth();
}
render() {
return (
<div ref={(r) => {this.childNode = r}}>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
父组件:
class ParentComp extends Component {
componentDidMount() {
//Access the child component function from here
this.childComponent.getWidth();
}
render() {
return (
<ChildComp
ref={(r) => {this.childComponent = r}} />
);
}
}
Run Code Online (Sandbox Code Playgroud)
但请记住,当无法以声明方式完成任务时,请使用上述方法。
我想说,从技术上来说,这似乎是不可能的。JSX
<div className="large-box"/>
Run Code Online (Sandbox Code Playgroud)
不是指 DOM 元素(渲染后就有宽度),而是指 React 元素,它是一个内存中的对象,描述如何创建DOM 元素。由于 React 元素没有渲染,甚至没有连接到浏览器中的实际 DOM,因此它无法知道宽度。
请记住,React 可以在服务器上呈现 - 服务器无法知道不同计算机上的浏览器将显示什么。
我也同意佩德罗·纳西门托 (Pedro Nascimento) 指出的观点——这个解决方案可能最好通过其他方式解决,但如果没有上下文,就很难提供帮助。
| 归档时间: |
|
| 查看次数: |
10599 次 |
| 最近记录: |