我有一个元素包装器来获取我需要传递给子元素的父元素的高度。
我正在通过 ref
获取和设置高度
我正在将 child 传递给 parent ,需要将高度传递给 child 。
class WrapElement extends React.Component<{element: any},any> {
constructor(props: any) {
super(props);
this.getHeight = this.getHeight.bind(this);
this.setHeight = this.setHeight.bind(this);
if (this.props.element) window.addEventListener('resize', this.setHeight);
}
getHeight() {
let { clientHeight }: any = this.refs.elemWrapper;
return clientHeight;
}
setHeight() {
this.setState({wrapperHeight: this.getHeight()})
}
componentDidMount() {
this.setHeight();
}
shouldComponentUpdate() {
return !this.state || this.getHeight() !== this.state.wrapperHeight;
}
componentDidUpdate() {
this.setHeight();
}
render() {
return <div
ref="elemWrapper"
>
{this.props.element? <this.props.element wrapperHeight={this.state.wrapperHeight} /> : 'no render'}
</div>
}
}
我确定<this.props.element />
无效,但我不知道如何通过 wrapperHeight
给 children 。
最佳答案
您可以使用 React.cloneElement
克隆元素并传递额外的属性,
{
this.props.element? React.cloneElement(
this.props.element,
{ wrapperHeight: this.state.wrapperHeight
}):
'no render'
}
关于javascript - 将属性添加到通过 props 传递到另一个组件的 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52474506/