我有一个对象:
{
"products": [
{
"id": 1,
"category": "Milk & meat",
"products": {
"product1": ["Name", "Recipe", "Photo"]
}
}
}
并且它的映射如下:
return (
<div className="box list">
{this.props.products
.map((product, ind) =>
<div key={ind}>
<h2>{product.category}</h2>
{Object.values(product.products).map(name => <li onClick={this.props.handleClickedProduct}>{name[0]}</li>)}
</div>)}
</div>
)
onClick方法将产品名称(数组中的[0])传递给其他组件。就是这样:
handleClickedProduct = (e) => {
this.setState({ clickedProduct: e.target.innerHTML });
}
我如何从同一个数组中设置状态[1]和[2]? 我想传递产品名称并保持食谱和照片的状态。
谢谢, 库巴
答案 0 :(得分:1)
class Example extends React.Component {
products = [
{
id: 1,
category: "Milk & meat",
products: {
product1: ["Name", "Recipe", "Photo"]
}
},
{
id: 2,
category: "Milk & bread",
products: {
product1: ["Name", "Recipe", "Photo"]
}
}
]
state = {
clickedProduct: null
}
handleClick = (product) => (e) => {
this.props.onClick(product)
}
render() {
return (
<div className="box list">
{this.products.map((product, ind) =>
<div key={ind}>
<h2>{product.category}</h2>
<ul>
{Object.values(product.products)
.map(pr => <li onClick={this.handleClick(pr)}>{pr[0]}</li>)}
</ul>
</div>)
}
</div>
)
}
}
class Handler extends React.Component {
handler = (e) => {
console.log(e)
}
render () {
return <Example onClick={this.handler}/>
}
}
ReactDOM.render(
<Handler />,
document.getElementById('container')
);
&#13;
将handleClickedProduct
更改为
handleClickedProduct = (name) => (e) => {
this.setState({ clickedProduct: e.target.innerHTML });}
在地图中,您只需this.handleClickedProduct(product.products)
并在handleClickedProduct
功能中使用它即可。