简体   繁体   中英

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() .

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?

thanks

Have a prop called something like onCalculateDistance and, in the child, do this:

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. Then you pass it down in the props of the component it will be called in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM