我在嘗試構建一個小的React應用程序,當用戶選擇肉製品時,用戶界面將顯示來自json數據文件的肉類。我有一個Products類作爲類ProductCategoryRow和SelectProduct函數的父類。我對如何在Products類中設置狀態並將道具傳遞給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;
在此先感謝
看起來你已經擁有的UpdateProduct與'SelectProduct'傳回了'prod'更新您的狀態。您需要將'selectedProduct = {this.state.selectedProduct}'作爲道具添加到'ProductCategoryRow'中,並且您應該可以訪問所選產品。或者我錯過了什麼? –
感謝您的幫助,不幸的是我在理解如何將一個道具傳遞給另一個組件時有點麻煩。您能否告訴我確切地在哪裏通過它。 – BigNom