我正在使用来自 api 的数据构建一个应用程序,我想在应用程序中包含用户的纬度和经度。
我的应用程序位于两个文件中:app.js
和 main.js
在 app.js
中,我像这样渲染组件:
render(<Main source="https://api.darksky.net/forecast/apikey/latitude,longitude?units=auto"/>, document.getElementById('app'));
纬度和经度当前已硬编码在组件源中,我想使它们动态化。
在我的 main.js
中,组件使用这样的 api:
componentDidMount() {
this.serverRequest = $.get(this.props.source, function (result) {
this.setState({
daily: result.daily.data,
hourly: result.hourly.data
});
}.bind(this));
}
我能够使用 HTML 地理位置获取用户位置 - 我想我应该将其存储在构造函数或 componentWillMount 中,但我需要一种方法将变量发送到 app.js
文件中主要组件的源 - 我想我应该使用像源一样的 Prop ,但我不知道如何
最佳答案
将经度和纬度作为 props 传递到组件中并在组件内组装 URL 可能是一个好方法:
render(<Main longitude={longitude} latitude={latitude} />, document.getElementById('app'));
<小时/>
componentDidMount() {
const url = `https://api.darksky.net/forecast/apikey/${this.props.latitude},${this.props.longitude}?units=auto`;
this.serverRequest = $.get(url, function (result) {
this.setState({
daily: result.daily.data,
hourly: result.hourly.data
});
}.bind(this));
}
关于javascript - 在 React 中使用 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40532368/