首页 > 解决方案 > 将 div 放在 StickyContainer 组件之间以使其具有粘性

问题描述

https://codesandbox.io/s/0prxxxvy0n

class App extends React.Component {
  render() {
    console.log("App---->");
    return (
      <StickyContainer>
        {/* Other elements can be in between `StickyContainer` and `Sticky`,
        but certain styles can break the positioning logic used. */}

        <div>
          I am sticky------------------------------------------------------->
        </div>

        <Sticky>
          {({
            style,

            // the following are also available but unused in this example
            isSticky,
            wasSticky,
            distanceFromTop,
            distanceFromBottom,
            calculatedHeight
          }) => <header style={style}>{}</header>}
        </Sticky>
        <SearchBar />
        <div>I am sticky</div>
        <WholeText />
        <UploadDocuments />
        <VerticalLinearStepper />
        {/* ... */}
      </StickyContainer>
    );
  }
}

标签: javascripthtmlreactjsreduxmaterial-ui

解决方案


正如文档所说,您需要将您的 div 放在组件的渲染回调中,即

class App extends React.Component {
  render() {
    console.log("App---->");
    return (
      <StickyContainer>
        <Sticky>
          {({ style }) => <div style={style}>I am sticky</div>}
        </Sticky>
        <SearchBar />
        <div>I am sticky</div>
        <WholeText />
        <UploadDocuments />
        <VerticalLinearStepper />
        {/* ... */}
      </StickyContainer>
    );
  }
}

在这种情况下,“渲染回调”只是意味着组件的子<Sticky>组件需要是一个返回应该呈现的内容的函数。这允许父级通过函数的参数传递附加信息以用于渲染子级。将函数指定为子函数的语法是:

<Parent>{/*function goes here*/}</Parent>

在上面的示例中,函数部分({ style }) => <div style={style}>I am sticky</div>假定将传递给函数的参数是具有style属性的对象,然后函数使用该样式返回 div 元素。

如果您查看react-sticky 代码,您会发现在其render方法中它执行以下操作:

  const element = React.cloneElement(
      this.props.children({
        isSticky: this.state.isSticky,
        wasSticky: this.state.wasSticky,
        distanceFromTop: this.state.distanceFromTop,
        distanceFromBottom: this.state.distanceFromBottom,
        calculatedHeight: this.state.calculatedHeight,
        style: this.state.style
      }),
      {
        ref: content => {
          this.content = ReactDOM.findDOMNode(content);
        }
      }
    );

当它调用 时this.props.children(...),它将执行您指定为子函数的函数,您可以看到它传递给函数的对象的最后一个属性是该style属性。


推荐阅读