javascript - 将 div 放在 StickyContainer 组件之间以使其具有粘性
问题描述
- 我试图让一个 div 粘在反应中。
- 所以我包含了 react-sticky 包。
- 并将 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>
);
}
}
解决方案
正如文档所说,您需要将您的 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
属性。
推荐阅读
- angular - 如何构建具有不同环境的角度项目
- python - 将 csv 文件中的字符串与日志文件匹配的正确方法是什么?
- node.js - 使用“pg:psql”命令连接 heroku 数据库时“连接超时”
- sql-server - 使用 SQL Server Ping IP 地址
- ajax - 如何在这个 wordpress 循环中添加加载更多按钮 ajax 按钮?
- c# - 相同表/类的 SQL 表设计
- c# - C# 为 ASP.NET Core 使用 System.Data.DataSet?
- django - IIS 上 django 中 POST 请求的状态 500
- c# - EF 6.0 未从具有多个 DBcontexts 的数据库生成的值返回 PK 键值
- jenkins - 如何使用 ${currentBuild.result} 表示“SUCCESS”而不是“null”