【发布时间】:2019-08-12 19:17:36
【问题描述】:
我正在尝试使用在 child.js 中的函数中生成的值并将其传递给 parent.js,以便我可以使用此值来过滤子数组。
Child.js
const returnDistance = () => {
const dist = getDistance(userLat, userLng, lat, lng).toFixed(1);
this.props.onCalculateDistance(dist);
return dist;
}
return dist 是生成的值,我需要在 parent.js 中访问
Parent.js
// The callback function
distanceChange = (dist) => {
console.log(dist)
return dist;
}
//The map to render child.js data. Im passing distanceChange as a prop.
{filteredResults.filter(({ node }) => (node.onCalculateDistance >= 0)).map(({ node }) => {
return (
<SpaceWrapper key={node.id}>
<Space node={node} onCalculateDistance={this.distanceChange} />
</SpaceWrapper>
)
}
)}
我在这里遗漏了什么明显的东西吗? distanceChange 的 console.log 返回 child.js 节点的所有值,但在用作道具时返回 undefined。
如何让函数运行,以便使用返回值过滤结果?
谢谢
【问题讨论】:
-
不确定你在用下面的代码做什么,你想检查 node.dist 吗?
node.onCalculateDistance >= 0 -
所以这只是一个冗长的例子,但我试图过滤掉例如大于 5 的结果,但我在某处感到困惑,无法弄清楚如何获得实际的子函数中的值。
-
你能把你的代码添加到codesandbox吗?
-
简短的回答是:你没有。道具按定义被传递给孩子,孩子不能变异。代码中这些项目的实际关系是什么,非常不清楚。
node被传递似乎很复杂,因此需要加以说明。您使用代码生成器这一事实可能会使问题复杂化,添加“非初学者”代码会使编辑和理解结果变得更加困难。 -
也不清楚为什么
parent需要dist。当您写“过滤子元素数组”时,您是在谈论与上述child不同类型的子组件吗?您的parent代码示例中还缺少任何 state 的概念。
标签: javascript arrays reactjs gatsby