最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to export a state(user selected value) from one component to another component in React? - Stack Overflow

programmeradmin5浏览0评论

I am trying to get the name of the city and use it to make up an ajax call in react. I am getting the name of the city from a dropdown menu in this.state.selectValue and able to display on console in the Drop ponent. I would like to take the value is name of city into my Weather ponent which is written as another jsx file. Please let me know how to acplish thi, referring to the code below. Thanks in Advance.

My Drop Component

    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 ponent 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;

My Weather Component

    import React from 'react';
    var WeatherReport = React.createClass({

getInitialState: function() {      
    return {count: 0};      
},
ponentWillMount: function() {
    console.log("Inside ponentWillMount");
},
ponentDidMount: function() {
    console.log("Inside ponentDidMount");
    var _FreeApiBaseURL = '/';
    var _FreeApiKey = '592042b57a7e48369e4110703160508';
    var input = {
        city: "Bengaluru",// I need to replace "Bengaluru" with the value imported from Drop ponent 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;

I am trying to get the name of the city and use it to make up an ajax call in react. I am getting the name of the city from a dropdown menu in this.state.selectValue and able to display on console in the Drop ponent. I would like to take the value is name of city into my Weather ponent which is written as another jsx file. Please let me know how to acplish thi, referring to the code below. Thanks in Advance.

My Drop Component

    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 ponent 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;

My Weather Component

    import React from 'react';
    var WeatherReport = React.createClass({

getInitialState: function() {      
    return {count: 0};      
},
ponentWillMount: function() {
    console.log("Inside ponentWillMount");
},
ponentDidMount: function() {
    console.log("Inside ponentDidMount");
    var _FreeApiBaseURL = 'http://api.worldweatheronline./premium/v1/';
    var _FreeApiKey = '592042b57a7e48369e4110703160508';
    var input = {
        city: "Bengaluru",// I need to replace "Bengaluru" with the value imported from Drop ponent 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;
Share Improve this question asked Aug 9, 2016 at 4:48 Chiraag KashyapChiraag Kashyap 911 gold badge2 silver badges9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

Solution 1

If there's a parent ponent that contains both Drop and Weather, you can set selectValue as a state in the parent ponent. Than selectValue can be passed from the parent ponent to Drop and Weather as a prop.

Furthermore, the handleChange event will also have to be defined in the parent ponent (so that it can update the selectValue state) and passed as another prop to Drop to be set as the onChange for the select.

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>
    );
  }
});

https://jsfiddle/joshdsantos/Lar10t4a/2/

Solution 2

If a parent ponent is just not possible - than you might want to check out Flux as a way to manage your data, as suggested by Facebook. https://facebook.github.io/react/tips/municate-between-ponents.html

Update using {this.props.children} and props

In the case of using {this.props.children} use: {React.cloneElement(this.props.children, {selectValue: this.state.selectValue})}

Docs: https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement

Updated Fiddle: https://jsfiddle/joshdsantos/Lar10t4a/10/

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论