我正在尝试构建一个小的React应用程序,当用户选择肉类产品时,ui将显示json数据文件中的肉类。我有一个Products类作为ProductCategoryRow类和SelectProduct函数的父类。关于如何在Products类中设置状态并将props传递给ProductCategoryRow和SelectProduct,我有点困惑。
function SelectProduct (props) {
const products = ['All', 'Beef', 'Lamb', 'Poultry'];
return (
<ul className='products'>
{products.map(function (prod) {
return (
<li
style={prod === props.selectedProduct ? { color: '#d0021b' }:null}
onClick={props.onSelect.bind(null, prod)}
key={prod}>
{prod}
</li>
)
})}
</ul>
)};
class ProductCategoryRow extends React.Component {
constructor(props) {
super(props);
this.state = {
list: list,
};
this.onDismiss = this.onDismiss.bind(this);
}
onDismiss(id) {
const isNotId = item => item.objectID !== id;
const updatedList = this.state.list.filter(isNotId);
this.setState({ list: updatedList });
}
render() {
return (
<div className="container">
{ this.state.list.map(item =>
<div key={item.objectID} className="product-category-row">
<div>{item.category}</div>
<div>{item.meatCut}</div>
<div>{item.cooking}</div>
<div>{item.price}</div>
<div>
<button
onClick={() => this.onDismiss(item.objectID)}
type="button"
>
Dismiss
</button>
</div>
</div>
)}
</div>
)
}
}
SelectProduct.propTypes = {
selectedProduct: PropTypes.string.isRequired,
onSelect: PropTypes.func.isRequired,
}
class Products extends React.Component {
constructor (props) {
super(props);
this.state = {
selectedProduct: 'All',
lists: null
};
this.updateProduct = this.updateProduct.bind(this);
}
componentDidMount () {
this.updateProduct(this.state.selectedProduct);
}
updateProduct(prod) {
this.setState(function () {
return {
selectedProduct: prod,
lists: null
}
})
}
render() {
return (
<div>
<SelectProduct
selectedProduct={this.state.selectedProduct}
onSelect={this.updateProduct}
/>
<ProductCategoryRow />
</div>
)
}
}
export default Products;
提前致谢
答案 0 :(得分:0)
选择产品时,您已经在更新父组件状态,这很好!现在,您需要在{1}}组件中将this.state.selectedProduct
作为ProductCategoryRow
道具传递到您的渲染方法中:
selectedProduct