简体   繁体   English

如何从其他组件调用/执行方法/函数

[英]How to call/execute method/function from another component react

I will want to know, if is possible call or execute a method or function from another component. 我想知道,是否可能从另一个组件调用或执行方法或函数。

I would like to run asynchronously the function that is the tableInformacion.js , which has a request get , but after the call of the post request is made that I have in address.js . 我想异步运行tableInformacion.js函数,该函数有一个请求get ,但是在调用post请求post ,我的地址就在address.js中

address.js address.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import request from 'superagent';
import {getSolarDayInformation} from './tableInformation.js';

import '../styles/main.css';

class AddressInput extends Component{

    constructor(){    
        super();
        this.state = {
            address: "",
            api:"http://maps.google.com/maps/api/geocode/json?address=",
            direccion: "",
            latitud: "",
            longitud:""          
        };
    } 

    render(){
        return(
            <div> 

                <form>      

                    <input type="text" 
                           value={this.state.address} 
                           onChange={this.updateAdress.bind(this)}
                           placeholder="Escriba la direccion"/>

                    <button onClick={this.getAddressGeo.bind(this)}>Consultar</button> 
                </form>

                <ul className="None-Style">
                    <li><label>Direccion:</label>{this.state.direccion}</li>
                    <li><label>Latitud:{this.state.latitud}</label></li>
                    <li><label>Longitud:{this.state.longitud}</label></li>
                </ul>
            </div> 
        )
    }

    updateAdress(event){
        this.setState({
            address: event.target.value
        });
    }

    getAddressGeo(e){

        e.preventDefault();
        const apiUrl = this.state.api + this.state.address;

        request.post(apiUrl).then((res) => {

            const direccionCompleta = res.body.results[0].formatted_address; 
            const Latitud = res.body.results[0].geometry.location.lat;
            const Longitud = res.body.results[0].geometry.location.lng;             

           this.setState({
                direccion: direccionCompleta,
                latitud: Latitud, 
                longitud: Longitud
            })

        })
        .catch((err) => {
            console.log(err.message);
        });

        getSolarDayInformation();

    } 
}

export default AddressInput;

tableInformacion.js tableInformacion.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import request from 'superagent';

class TableConsumeInformation extends Component{

    constructor(){
        super();
        this.state = {
            apiSolarInformation: 'https://asdc-arcgis.larc.nasa.gov/cgi-bin/power/v1beta/DataAccess.py?request=',
            parameters:'execute&identifier=SinglePoint&parameters=ALLSKY_SFC_SW_DWN&',
            startDate:'0101&',
            endDate:'1231&',
            comunity: 'userCommunity=SSE&tempAverage=DAILY&outputList=JSON,ASCII&',
            latitudePlace:'lat=',
            longitudePlace:'&lon=',
            anonymous:'&user=anonymous'
        };
    }

    render(){
        return(
            <div>
                <h2>Information Energy</h2>
                <table></table>
            </div>
        );
    }

    getSolarDayInformation(){
        apiSolarUrl = 'https://asdc-arcgis.larc.nasa.gov/cgi-bin/power/v1beta/DataAccess.py?request=execute&identifier=SinglePoint&parameters=ALLSKY_SFC_SW_DWN&startDate=20170101&endDate=20171231&userCommunity=SSE&tempAverage=DAILY&outputList=JSON,ASCII&lat=11.373&lon=-72.253&user=anonymous';
        request.get(apiSolarUrl).then((req, res) => {
            console.log(res.body);
        });
    }

}

export default TableConsumeInformation;

I assume you are talking about the getSolarDayInformation function in this case. 我假设您在这种情况下正在谈论getSolarDayInformation函数。

In your case here, it looks like the easiest thing to do would be to refactor your function into its own file and import it into all the places its needed. 就您的情况而言,看起来最简单的事情是将函数重构到其自己的文件中,并将其导入所需的所有位置。 There is no reason for it to be a object method as it has no dependency on the object state. 它没有理由成为对象方法,因为它不依赖于对象状态。

You could create a helper functions file , something like 您可以创建一个辅助函数文件 ,例如

helper.js

export const getSolarDayInformation = () => {
    ...
}

Then, import the method in your other file(s) 然后,将该方法导入其他文件中

import {getSolarDayInformation} from 'path/to/your/file';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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