为什么两次使用组件时不需要密钥支架?
我以为我理解了 key prop 在 React 中的作用,但后来我无法理解为什么重复使用相同的组件不需要 key prop,如下例所示。
假设我有一个看起来像这样的 Like 组件:
function Like() {
const [c, setC] = useState(0);
return (
<div>
<h3>Liked: {c} times</h3>
<button onClick={() => setC(c+1)}>Like!</button>
</div>
);
}
在 App 组件中,我有
<div>
<Like />
<Like />
</div>
React 似乎并没有因为有两个相同的组件而烦恼。只要点赞,计数就会正确更新!按钮被按下。
I thought I understood the role of key prop in react but then I couldn't figure why using the same component repeatedly does not require key prop such as in the following example.
Say I have a Like component that looks like this:
function Like() {
const [c, setC] = useState(0);
return (
<div>
<h3>Liked: {c} times</h3>
<button onClick={() => setC(c+1)}>Like!</button>
</div>
);
}
And in the App component, I have
<div>
<Like />
<Like />
</div>
React doesn't seem to be bothered by the fact that there are two identical components. The count is updated correctly whenever the Like! button is pressed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论