如何将道具从父组件渲染到子组件?
Posted
技术标签:
【中文标题】如何将道具从父组件渲染到子组件?【英文标题】:How to render props from parent component to child? 【发布时间】:2021-07-22 05:36:44 【问题描述】:我正在尝试遍历数组并将标题和描述发送到子组件。但是,子组件无法识别我在父组件中分配给它的道具。
News.js:
const AllNews = [
title: 'Reverse The Online Gambling Ban',
description: 'The MPA comes with three different sizes of foam and silicone tips and a carrying pouch.'
,
title: 'Successful Myspace Profile',
description: 'All users on MySpace will know that there are millions of people out there.'
,
title: 'Home Audio Recording For Everyone',
description: 'The number of friends and acquaintances will grow in a large number. This is what you should be looking for.'
,
title: 'Buying Used Electronic Test Equipment',
description: 'People after all will make friends after reading about you. If you have an ugly profile, there is no way they will want to date you.'
]
export default function News()
const classes = useStyles();
const listNews = AllNews.forEach(news =>
<Singlenews title=news.title description=news.description/>
)
return (
<div>
listNews
</div>
)
Singlenews.js:
export default function Singlenews(props)
const classes = useStyles();
const title, description = props
return (
<div className=classes.group4>
<div className=classes.bitmap/>
<div className=classes.flexCol>
<div className=classes.reverseTheOnlineG>
title
</div>
<div className=classes.group4>
<p className=classes.theMpaComesWithT>
description
</p>
<div className=classes.oval/>
</div>
</div>
</div>
)
【问题讨论】:
我的蠢驴没有返回任何东西...... 【参考方案1】:在这部分:
const listNews = AllNews.forEach(news =>
<Singlenews title=news.title description=news.description/>
)
您正在循环遍历AllNews
中的每个项目并使用forEach
函数创建Singlenews
组件。这绝对是正确的想法,问题是forEach
函数返回undefined
(https://developer.mozilla.org/en-US/docs/Web/javascript/Reference/Global_Objects/Array/forEach)。所以listNews
在这种情况下实际上等于undefined
。
我的建议是查看 JavaScript 中的 map
函数 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)。此函数将回调映射到数组的每个元素并返回一个新数组,其中包含回调的返回值。因此,在这种情况下,您可以将 <SingleNews>
组件映射到 AllNews
中的每个元素,就像您已经拥有它一样向下传递道具:
const listNews = AllNews.map(news =>
return <Singlenews title=news.title description=news.description/>
)
这样,listNews
是一个由 <Singlenews>
组成的数组,就像您想要的那样,并且正确设置了道具。不是道具的问题,是循环的问题!
【讨论】:
好的,谢谢!我刚刚用您发布的确切解决方案解决了这个问题。非常感谢您抽出宝贵的时间!【参考方案2】:试试这个const listNews = AllNews.map(news => <Singlenews title=news.title description=news.description/>);
而不是const listNews = AllNews.forEach(news => <Singlenews title=news.title description=news.description/> )
【讨论】:
以上是关于如何将道具从父组件渲染到子组件?的主要内容,如果未能解决你的问题,请参考以下文章