Javascript 如何在React中将状态(用户选择的值)从一个组件导出到另一个组件?

Javascript 如何在React中将状态(用户选择的值)从一个组件导出到另一个组件?,javascript,reactjs,Javascript,Reactjs,我正在尝试获取城市的名称,并使用它在react中生成一个ajax调用。我从this.state.selectValue中的下拉菜单中获取城市名称,并能够在Drop组件的控制台上显示。我想将值is name of city放入我的天气组件中,该组件作为另一个jsx文件编写。请让我知道如何完成这一点,参考下面的代码。 提前谢谢 我的下降组件 import React from 'react'; import Dropdown from 'react-bootstrap/lib/dro

我正在尝试获取城市的名称,并使用它在react中生成一个ajax调用。我从this.state.selectValue中的下拉菜单中获取城市名称,并能够在Drop组件的控制台上显示。我想将值is name of city放入我的天气组件中,该组件作为另一个jsx文件编写。请让我知道如何完成这一点,参考下面的代码。 提前谢谢

我的下降组件

    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 &nbsp;
                <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;
从“React”导入React;
从“react bootstrap/lib/Dropdown”导入下拉列表;
var Drop=React.createClass({
getInitialState(){
返回{selectValue:'Bengaluru'};
},
手变(e){
this.setState({selectValue:e.target.value});
},
render(){
var message='You selected'+this.state.selectValue;//我想将此(this.state.selectValue)值导出到另一个jsx文件中的天气组件中。
返回(

选择你的城市
班加罗尔
海得拉巴
钦奈
孟买
{message}

); } }); 出口违约率下降;
我的天气组件

    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 &nbsp;
                <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;
从“React”导入React;
var WeatherReport=React.createClass({
getInitialState:函数(){
返回{count:0};
},
componentWillMount:function(){
日志(“内部组件将安装”);
},
componentDidMount:function(){
日志(“内部组件安装”);
var\u FreeApiBaseURL=http://api.worldweatheronline.com/premium/v1/';
var _FreeApiKey='592042B57A7E48369E410703160508';
变量输入={
城市:“Bengaluru”//我需要用从Drop组件(即this.state.selectValue)导入的值替换“Bengaluru”。
天数:1
};
var url=_FreeApiBaseURL+'weather.ashx?key='+_FreeApiKey+'&q='+input.city+'&format=json&num_of_days='+input.days;
console.log(url);
$.ajax({
url:url,
数据类型:“json”,
键入:“GET”,
数据:{
maxTemp:“”,
明特姆:“,
湿度:“,
风速:“
},
async:false,
contentType:“应用程序/json”,
成功:功能(数据){
log(JSON.stringify(data));
log(JSON.stringify(data.current_condition));
},
错误:函数(e){
控制台日志(e.message);
}
});
},
render:function(){
返回(

日期。。。

最高温度。。。

最低温度。。。

湿度

风速

返回 ); } }); 导出默认天气报告;
解决方案1

如果父组件同时包含Drop和Weather,则可以将selectValue设置为父组件中的状态。然后,selectValue可以作为道具从父组件传递给Drop和Weather

此外,handleChange事件还必须在父组件中定义(以便它可以更新selectValue状态),并作为另一个道具传递给Drop,以设置为selectValue的onChange

var Parent = React.createClass({
    getInitialState: function() {
    return {selectValue: 'Bengaluru'}
  },
  handleChange: function(e) {
    this.setState({selectValue: e.target.value});
  },
  render: function() {
    return (
        <div>
        <Drop selectValue={this.state.selectValue} handleChange={this.handleChange} />
        <Weather selectValue={this.state.selectValue} />
      </div>
    );
  }
});

var Drop = React.createClass({
    render: function() {
    return (
        <div>
        Drop Component:
        <select id="cityList" value={this.props.selectValue} onChange={this.props.handleChange}>
          <option value="Bengaluru">Bengaluru</option>
          <option value="Hyderabad">Hyderabad</option>
          <option value="Chennai">Chennai</option>
          <option value="Mumbai">Mumbai</option> 
        </select>
      </div>
    );
  }
});

var Weather = React.createClass({
    render: function() {
    return (
        <div>Weather Component: {this.props.selectValue}</div>
    );
  }
});
var Parent=React.createClass({
getInitialState:函数(){
返回{selectValue:'Bengaluru'}
},
handleChange:函数(e){
this.setState({selectValue:e.target.value});
},
render:function(){
返回(
);
}
});
var Drop=React.createClass({
render:function(){
返回(
下拉组件:
班加罗尔
海得拉巴
钦奈
孟买
);
}
});
var Weather=React.createClass({
render:function(){
返回(
天气组件:{this.props.selectValue}
);
}
});

解决方案2

如果不可能使用父组件,那么您可能希望按照Facebook的建议,使用Flux作为管理数据的一种方式

使用{this.props.children}和props更新

在使用{this.props.children}的情况下,请使用:
{React.cloneElement(this.props.children,{selectValue:this.state.selectValue}}}

文件:


更新的Fiddle:

我使用了{this.props.children}来启用路由。在这种情况下,如何设置selectvalue?请帮我工作好。。。非常感谢。