在父组件componentDidMount完成后渲染子组件

时间:2018-07-30 21:06:23

标签: javascript reactjs

我有一个第三方图书馆正在尝试使用。它有一个特殊的道具,允许您传递用于获取DOM元素并返回底值的字符串。

<Sticky bottomBoundary="#some-id">
    <MyChildComponentMightBeANavigationOrAnything />
</Sticky>

该组件获取ID并确定底值,因此它知道何时从粘性状态释放自己。这个ID基本上是DOM中的另一个元素。因此,当该元素的底值到达视口的顶部时,允许粘性组件随着用户滚动而向上移动。我有的问题是我需要添加一个偏移量。粘性组件可让您传递数字值。

<Sticky bottomBoundary={1200}>
    <MyChildComponentMightBeANavigationOrAnything />
</Sticky>

无论粘性元素的高度是多少,我都需要添加一个偏移量。因此,可以说“#some-id”元素为1200px,粘性元素的高度为50,在将值传递到bottomBoundary = {}之前,我需要能够获取“#some-id”并减去50。 。我的计算值将是bottomBoundary = {1150}。

我尝试了以下方法。我创建了一个包装Sticky的组件,如下所示:

export class WrapperSticky extends React.Component {

    constructor(props) {
        super(props);

        this.boundary = null;
    }

    componentDidMount() {
        const el = document.querySelector(this.props.bottomBoundary);
        const rect: any = el.getBoundingClientRect();
        this.boundary = rect.bottom - 50;

        console.log(this.boundary);
    }

    render() {
        return (
            <Sticky innerZ={2000} bottomBoundary={this.boundary}>{this.props.children}</Sticky>
        );
    }
}

我添加了如下标记:

<WrapperSticky bottomBoundary="#hero" offset={true}>
    <MyChildComponentMightBeANavigationOrAnything />
</WrapperSticky >

在WrapperSticky内部,我尝试在componentDidMount方法中进行计算并将结果传递到Sticky组件中。明显的问题是Sticky组件尝试在包装器组件完成计算之前找到该值。

有没有办法优雅地做到这一点。我是个新手,所以应该学习任何文章或文档。

谢谢。

2 个答案:

答案 0 :(得分:2)

您需要为此使用组件状态。计算完成后-更新状态,以便组件使用计算值重新渲染。

this.state.boundarythis.boundary

  1. 将边界值放入组件的状态将通过重新呈现其任何更改来帮助您 (即调用setState)。
  2. 仅当值不应影响渲染结果时,才应使用普通类字段。

代码如下:

class WrapperSticky extends Component {
  state = {
    boundary: undefined,
  }

  componentDidMount() {
    const el = document.querySelector(this.props.bottomBoundary)
    const rect = el.getBoundingClientRect()
    const boundary = rect.bottom - 50

    this.setState({ boundary })
  }

  render() {
    const { boundary } = this.state

    return boundary === undefined
      ? null // or placeholder
      : (
        <Sticky innerZ={2000} bottomBoundary={boundary}>
          {this.props.children}
        </Sticky>
      )
  }
}

答案 1 :(得分:0)

您可能在WrapperSticky状态下有一个布尔标志,用于确定是否已完成计算。最初是假的,并且render返回<></>。在componentDidMount中,执行计算后,将标志设置为true,这将触发重新渲染,从而将子级渲染为真实。至少应该可以正常工作(我已经使用subProps状态字段进行了类似的here操作),尽管使用一些更高级的生命周期挂钩可能会有更好的方法。

相关问题