将状态(索引)传递给几个孩子
在学习了如何将状态传递给孩子之后,我现在想知道如何在孩子之间做到这一点。
Parent:
const PostTemplate = ({ data }) => {
const [isIndex, setIndex] = useState(0);
return (
<>
<Slider
setIndex={isIndex}
{...data}
/>
<Views
setIndex={setIndex}
{...data}
/>
</>
);
};
Child1 (Views):
const Views = (data) => {
return (
<div>
{data.views.edges.map(({ node: view }, index) => (
<div
onClick={() => {
data.setIndex(index);
}}
>
<p>Hello</p>
/>
</div>
))}
</div>
);
};
Child2 (Slider):
const Slider = (data) => {
return (
<Swiper initialSlide={data.isIndex}>
{data.views.edges.map(({ node: view }) => (
<SwiperSlide>Slide</SwiperSlide>
))}
</Swiper>
);
};
这会返回一个相当奇怪的错误:undefined is not an object (evaluating 'el.classList')
。
我想做的是将 Views 索引传递给 Slider。
感谢您的帮助!
After learning how to pass a state to a child, I am now wondering how to do it between children.
Parent:
const PostTemplate = ({ data }) => {
const [isIndex, setIndex] = useState(0);
return (
<>
<Slider
setIndex={isIndex}
{...data}
/>
<Views
setIndex={setIndex}
{...data}
/>
</>
);
};
Child1 (Views):
const Views = (data) => {
return (
<div>
{data.views.edges.map(({ node: view }, index) => (
<div
onClick={() => {
data.setIndex(index);
}}
>
<p>Hello</p>
/>
</div>
))}
</div>
);
};
Child2 (Slider):
const Slider = (data) => {
return (
<Swiper initialSlide={data.isIndex}>
{data.views.edges.map(({ node: view }) => (
<SwiperSlide>Slide</SwiperSlide>
))}
</Swiper>
);
};
This returns a rather strange error: undefined is not an object (evaluating 'el.classList')
.
What I would like to do is pass the index of Views to Slider.
Thanks for all the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Props:
数据流:
在您的示例中,
PostTemplate
是父级,而Views
& 是父级。Slider
是子项。PostTemplate
拥有并管理索引数据(状态)。PostTemplate
将发送索引数据(状态)到子组件:Views
&Slider
Views
需要更改Index的值。因此,父组件还将其自己的索引更改处理程序传递给 Views 组件,这是您的相关代码的一个工作示例:
在 CodePen 上尝试
Props:
Data Flow:
In your example
PostTemplate
is parent andViews
&Slider
are child.PostTemplate
own and manage index data (state).PostTemplate
will send index data (state) to child components:Views
&Slider
Views
need to change the value of Index. So parent component also pass it's own index change handler toViews
componentViews
component calls the change handler it got from it's parent as props when it needs to change Index value.Here is a working example from your code in question:
Try it on CodePen