javascript - 将属性添加到通过 props 传递到另一个组件的 react 组件

标签 javascript reactjs

我有一个元素包装器来获取我需要传递给子元素的父元素的高度。

我正在通过 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/

相关文章:

javascript - 从 React 中的 CORS API 调用中得到 undefined

amazon-web-services - 构建后自动将静态网站文件部署到 S3

javascript - 未在浏览器中设置 Cookie

javascript - 为什么子组件更新但不重新渲染 Reactjs

javascript - 使用 reactjs 实现 Facebook API 登录

javascript - Hot Towel SPA添加用户认证登录页面

javascript - jquery ui datepicker add 6month 在边缘情况下是错误的

javascript - 如何使用 CSS 渐变在模拟时钟上突出显示 25 分钟?

javascript - 使用 Three.js 中的箭头键围绕对象旋转相机

javascript - AJAX 请求未找到模型 ID