预期效果:点击按钮->调用函数add->添加对象this.color到数组products-colors组件App中的属性。示例:
colors: [{color:" green "}, {color:" black "}]->colors: [{color: "green"}, {color: "black"}, {color: "red "}]
错误:TypeError:无法读取未定义的属性“推送”
应用程序
class App extends React.Component {
state = {
products: [
{ id: 0, colors: [{color:"green"}, {color:"black"}], desc: "some desc" },
{ id: 1, colors: [{color:"yellow"}, {color:"purple"}], desc: "some desc1" }
],
index: null
};
add = (newColor) => {
let newProducts = [...this.state.products]
newProducts[index].colors.push(newColor);
this.setState({products: newProducts});
}
select = (index) => {
this.setState({
index: index
})
}
render() {
<div>
<ul>
{
this.state.products.map((product, index) => (
<Product
key={product.id}
product={product}
select={() => this.select(index)}
/>
))
}
</ul>
<Details
add={this.add}
/>
</div>
}
}
细节
class Details extends React.Component {
click1 = () => {
this.color = {
color: 'red'
}
this.props.add(this.color);
}
render() {
<div>
<button onClick={this.click1}></button>
</div>
}
}