私は都市の名前を取得しようとしていて、それを使ってajaxコールを反応させようとしています。私はthis.state.selectValueのドロップダウンメニューから街の名前を取得していて、Dropコンポーネントのコンソールに表示することができます。私は値を別のjsxファイルとして書かれている私の天気コンポーネントに都市の名前です。下のコードを参考にして、私はどのように達成するのか教えてください。 ありがとうございました。Reactの1つのコンポーネントから別のコンポーネントに状態(ユーザーが選択した値)をエクスポートする方法は?
マイドロップコンポーネント
import React from 'react';
import Dropdown from 'react-bootstrap/lib/dropdown';
var Drop = React.createClass({
getInitialState() {
return {selectValue: 'Bengaluru'};
},
handleChange(e) {
this.setState({selectValue: e.target.value});
},
render() {
var message = 'You selected ' + this.state.selectValue; // I want to export this (this.state.selectValue) value to my Weather component in another jsx file.
return (
<div>
<p>
Choose Your city
<select id="cityList" value={this.state.selectValue} onChange={this.handleChange}>
<option value="Bengaluru">Bengaluru</option>
<option value="Hyderabad">Hyderabad</option>
<option value="Chennai">Chennai</option>
<option value="Mumbai">Mumbai</option>
</select>
<p>{message}</p>
</p>
</div>
);
}
});
export default Drop;
マイ天気コンポーネント
import React from 'react';
var WeatherReport = React.createClass({
getInitialState: function() {
return {count: 0};
},
componentWillMount: function() {
console.log("Inside componentWillMount");
},
componentDidMount: function() {
console.log("Inside componentDidMount");
var _FreeApiBaseURL = 'http://api.worldweatheronline.com/premium/v1/';
var _FreeApiKey = '592042b57a7e48369e4110703160508';
var input = {
city: "Bengaluru",// I need to replace "Bengaluru" with the value imported from Drop component ie this.state.selectValue.
days: 1
};
var url = _FreeApiBaseURL + 'weather.ashx?key=' + _FreeApiKey + '&q=' + input.city + '&format=json&num_of_days=' + input.days;
console.log(url);
$.ajax({
url: url,
dataType: 'json',
type: 'GET',
data: {
maxTemp: "",
minTemp: "",
Humidity: "",
Windspeed: ""
},
async: false,
contentType: "application/json",
success: function(data) {
console.log(JSON.stringify(data));
console.log(JSON.stringify(data.current_condition));
},
error: function(e) {
console.log(e.message);
}
});
},
render: function() {
return (
<div>
<p>
Date ...
</p>
<p>
Maximum Temperature ...
</p>
<p>
Minimum Temperature ...
</p>
<p>
Humidity...</p>
<p>
Wind Speed...</p>
<button onClick={this.navigate.bind(this)}>
Back</button>
</div>
);
}
});
export default WeatherReport;
上記の更新を参照してください。 – joshdsantos
うまく動作...ありがとう –