[英]How to call/execute method/function from another component react
我想知道,是否可能從另一個組件調用或執行方法或函數。
我想異步運行tableInformacion.js函數,該函數有一個請求get
,但是在調用post
請求post
,我的地址就在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;
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¶meters=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¶meters=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;
我假設您在這種情況下正在談論getSolarDayInformation函數。
就您的情況而言,看起來最簡單的事情是將函數重構到其自己的文件中,並將其導入所需的所有位置。 它沒有理由成為對象方法,因為它不依賴於對象狀態。
您可以創建一個輔助函數文件 ,例如
helper.js
export const getSolarDayInformation = () => {
...
}
然后,將該方法導入其他文件中
import {getSolarDayInformation} from 'path/to/your/file';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.