问题描述
我在导航栏中有一个链接,该链接将我带到索引页上的锚点.目前,我不知道如何在组件上添加ID,因此必须将组件包装在div中,并为其指定ID以使其正常工作.理想情况下,我想简单地将锚点放置在组件本身上.
I have a link in a nav-bar that takes me to an anchor on the index page. Currently I don't know how to put an id onto the component, so I have to wrap the component in a div and give it an id for it to work. Ideally, I would like to simply put the anchor on the component itself.
这对我来说很好,但是我想知道这是否是使用React/Gatsby进行锚定的方法,还是有更好的方法?
This works fine for me, but I'm wondering if this is the way to do an anchor with React/Gatsby or is there a better way?
//Navbar, which is part of Layout
export default class NavBar extends Component {
render() {
return (
<NavContainer>
<Menu>
<ul>
<li>Home</li>
<li>About</li>
<li>Events</li>
<li>Blog</li>
<li>Mentorship</li>
<li>
<Link to="/#join-us">Join Us</Link>
</li>
</ul>
</Menu>
</NavContainer>
)
}
}
//Homepage
const IndexPage = ({ data, location }) => {
const { site, events, about, features, blogs } = data
const eventsEdges = events.edges
return (
<Layout>
<div id="join-us">
<JoinUs /> //Can't do <JoinUs id="join-us"/>
</div>
<BlogList blogs={blogs} fromIndex={true} />
</Layout>
)
}
推荐答案
您必须将 id
作为 props
传递给您的 JoinUs
组件.
首先,执行< JoinUs id ="join-us"/>
.现在, id
是组件的道具.
You have to pass id
as a props
to your JoinUs
component.
First of all, do <JoinUs id="join-us" />
. Now, id
is a props of your component.
const JoinUs = ({ id }) => (
<div id={id}>
...Your component stuff
</div>
);
其他方法
import React from 'react'
class JoinUs extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div id={this.props.id}>
... Your component stuff
</div>
);
}
}
export default JoinUs
这两种方法相似,但第一种更为简洁. JoinUs =({id})...
行允许您访问和分解道具.您可以从 props
获取属性 id
.现在,您不必用锚将组件包装在 div
中
The two methods are similar but the first one is more concise.The line JoinUs = ({ id }) ...
allows you to access and destructure props. You get property id
from your props
. Now, you don't have to wrap your component in a div
with an anchor
此处的更多信息: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
这篇关于向React/Gatsby组件添加ID以进行哈希链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!