给定非常简单的页面(假设已导入React和react-router @ 4):
// Current location: example.com/about
<Link to="/about/#the-team">See the team</Link>
// ... loads of content ... //
<a id="the-team"></a>
我希望上面的内容在单击“查看团队”后会向下滚动到ID标记的团队锚点。网址正确更新为:example.com/about#the-team
,但不会向下滚动。
我已经尝试过其他选择,例如,<a name="the-team"></a>
但我认为这不再是规范(也不起作用)。
github上有很多针对react-router @ v2的变通方法,但是它们依赖于BrowserRouter上存在的更新回调,而该回调在v4中不再存在。
给定一个<ScrollIntoView>
使用该元素的id滚动到的组件:
class ScrollIntoView extends React.Component {
componentDidMount() {
this.scroll()
}
componentDidUpdate() {
this.scroll()
}
scroll() {
const { id } = this.props
if (!id) {
return
}
const element = document.querySelector(id)
if (element) {
element.scrollIntoView()
}
}
render() {
return this.props.children
}
}
您可以在其中包装视图组件的内容:
const About = (props) => (
<ScrollIntoView id={props.location.hash}>
// ...
</ScrollIntoView>
)
或者,您可以创建一个匹配包装器:
const MatchWithHash = ({ component:Component, ...props }) => (
<Match {...props} render={(props) => (
<ScrollIntoView id={props.location.hash}>
<Component {...props} />
</ScrollIntoView>
)} />
)
用法是:
<MatchWithHash pattern='/about' component={About} />
一个完全充实的解决方案可能需要考虑边缘情况,但是我对上述情况进行了快速测试,并且似乎可行。
现在可以通过npm使用此组件。GitHub:https : //github.com/pshrmn/rrc
npm install --save rrc
import { ScrollIntoView } from 'rrc'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句