我将 移动selectedProduct
到Products
组件。然后我向 properties 添加了新值selectedProduct
。如何将此对象返回App
给products
数组的组件?
应用程序
class App extends Component {
constructor(){
super();
this.state {
products: [
{
color: ['black', 'orange']
desc: 'gfgfg'
},
{
color: ['yellow'],
desc: 'gfgfgfg'
}
]
}
}
add = (updateProduct) => {
const {products} = this.state;
this.setState({
products: [...products, updateProduct]
})
}
render () {
let selectedProduct = this.state.products[0];
return (
<div>
<ul>
{
this.state.products
.map((product, index) =>
<Product
key={index}
index={index}
product={product}
/>
)
}
</ul>
<Products
selectedProduct = {selectedProduct}
add={this.add}
/>
</div>
)
}
}
export default App;
产品
class Products extends Component {
constructor(){
super();
this.state = {
selectProduct: [{
color: ['black', 'orange', 'pink]
desc: 'gfgfg'
}]
}
}
componentDidUpdate (prevProps) {
if (prevProps.selectedProduct !== this.props.selectedProduct) {
this.setState({
selectProduct: this.props.selectedProduct
});
if (this.props.add) {
this.props.add(this.state.selectProduct)
}
}
}
render () {
return (
<div>
</div>
)
}
}
您需要将更改传播回 App,在您的情况下,您可以changeState
在父组件中设置一个函数并将其作为属性向下传播。有关更多信息,请参见此处如何在 React 中更新父状态?
有多种选择,但我建议使用钩子和上下文 API,例如:https : //upmostly.com/tutorials/how-to-use-the-usecontext-hook-in-react/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句