[英]React: How do I pass a returned function value to a parent component?
new to react so this is probably very obvious but I have a function that calculates distance between the user and the lat,lng of the component (from the state) and then returns the value with returnDistance()
. 是新的,所以这可能非常明显,但是我有一个函数可以计算用户与组件的lat,lng之间的距离(根据状态),然后使用returnDistance()
返回值。
export default class Space extends React.Component {
render() {
const userLat = this.props.userLat,
userLng = this.props.userLng;
let lat = this.props.node.latitude,
lng = this.props.node.longitude;
function getDistance(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLat = toRad(lat2 - lat1);
var dLon = toRad(lon2 - lon1);
var lat1 = toRad(lat1);
var lat2 = toRad(lat2);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
// Converts numeric degrees to radians
function toRad(Value) {
return Value * Math.PI / 180;
}
function returnDistance() {
return getDistance(userLat, userLng, lat, lng).toFixed(1);
}
return (
<Component>
{userLat ?
<ComponentDistance>
{returnDistance()}
<span>km</span>
</ComponentDistance>
: null }
</Component>
)
}
}
How do I pass the value of returnDistance()
to the parent component when I can't setState or props within render? 当我无法在render中设置setState或props时,如何将returnDistance()
的值传递给父组件?
thanks 谢谢
Have a prop called something like onCalculateDistance
and, in the child, do this: 有一个名为onCalculateDistance
类的道具,然后在孩子中执行以下操作:
function returnDistance() {
const dist = getDistance(userLat, userLng, lat, lng).toFixed(1);
this.props.onCalculateDistance(dist);
return dist;
}
And then in the parent, you can do this: 然后在父级中,您可以执行以下操作:
distanceChange(dist) {
// whatever you want, for example
this.setState({dist});
}
render() {
return (<Space onCalculateDistance=(this.distanceChange)/>)
}
Typically you would keep the returnDistance()
function in the parent component if you need access to its result there. 通常,如果需要在其中访问其结果,则可以将returnDistance()
函数保留在父组件中。 Then you pass it down in the props of the component it will be called in. 然后,将其传递到将被调用的组件的props中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.