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

问题描述 投票:0回答:2

我正在尝试将我的应用分解为更易于管理的组件。因此,我有一个名为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。如何将其传递给子组件?

javascript reactjs
2个回答
2
投票

您可以将其向下传递到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

我希望这会有所帮助!


2
投票

使用props

<LatestProduct product={product}/>
© www.soinside.com 2019 - 2024. All rights reserved.