【发布时间】:2021-03-12 04:47:13
【问题描述】:
我想在我的 MongoDB 中存储一个分配给父函数的 props 值,以便我可以基于该数组呈现组件,并且每个组件都有自己的函数。
我有一个这样的 JSON,我从我的 mongoDB 中获取,然后存储在 this.state.people
{
"_id": "60496f4e6478022895c0b1da",
"name": "Peter",
"imagepath": "./img/Peter.png",
},
{
"_id": "60496f4e6478022895c0b1da",
"name": "Tim",
"imagepath": "./img/Tim.png",
}
我将状态传递给子组件并渲染组件:
{props.people.map( result =>
<PeopleComponent
key={result._id}
name={result.name}
imagepath={result.imagepath}
/>
)}
到目前为止效果很好。
现在我无法解决的问题:
在我的父组件 App.js 中,我有函数 doSomethingWithPeter() 和 doSomethingWithTim()。如何将这些函数包含到 .map 中,以便在单击按钮时实际调用父函数?
我尝试在数据库中添加一个附加条目,添加:
"_id": "60496f4e6478022895c0b1da",
"name": "Tim",
"imagepath": "./img/Tim.png",
"function": "props.doSomethingWithTim()"
然后将其映射为:
{props.people.map( result =>
<PeopleComponent
key={result._id}
name={result.name}
imagepath={result.imagepath}
function={result.function}
/>)}
然后我得到Expected an assignment or function call and instead saw an expression
我通过 props 传递了函数,并尝试在 App.js 中使用 this.props.doSomethingWithTim = this.props.doSomethingWithTim.bind(this) 绑定它,但不知道我还能尝试什么。提前谢谢
【问题讨论】: