gpt4 book ai didi

javascript - React - 从嵌入式组件中的数组获取内容

转载 作者:行者123 更新时间:2023-11-28 14:11:23 25 4
gpt4 key购买 nike

我正在尝试将我的应用程序分解为更易于管理的组件。因此,我有一个名为 LatestProducts 的组件,然后在该组件中我将一个数组映射到子组件 LatestProduct。如何才能让子组件可以使用父组件的数据?

最新产品:

import LatestProduct from '../LatestProduct';

class LatestProducts extends Component {

constructor() {
super();
this.state = {
LatestProducts: []
}
}

...

render() {
const LatestProducts = this.state.LatestProducts;
return (
<div className="row">
{LatestProducts.map((product, index) => {
return (
<div key={index} className="product"><LatestProduct /></div>
);
})}
</div>
);
};
};

最新产品:

class LatestPost extends Component {

render() {
return (
<article className="product-container">
<h2>{product.title}</h2>
</article>
);
};
};

这显然会返回错误,因为 productLatestProduct 组件上未定义。如何将其传递给子组件?

最佳答案

你可以通过props将其传递下来。

我会在 LatestProducts 组件中执行以下操作:

LatestProducts.map((product, index) => {
return <div key={index} className="product"><LatestProduct product={product} /></div>
})

并在您的 LatestPost 组件中访问它,如下所示:

 class LatestPost extends Component {
constructor(props) {
super(props);
}

render() {
return <article className="product-container">
<h2>{this.props.product.title}</h2>
</article>
};
};

建议阅读的文档是 Components and Props来自 React 网站。

希望这会有所帮助!

关于javascript - React - 从嵌入式组件中的数组获取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59330280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com