我正在尝试将我的应用分解为更易于管理的组件。因此,我有一个名为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>
);
};
};
LatestProduct:
class LatestPost extends Component {
render() {
return (
<article className="product-container">
<h2>{product.title}</h2>
</article>
);
};
};
这显然会返回错误,因为在product
组件上未定义LatestProduct
。如何将其传递给子组件?
您可以将其向下传递到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>
};
};
建议阅读的文档是React网站的Components and Props。
我希望这会有所帮助!
使用props
<LatestProduct product={product}/>