如何将值返回到父组件?

时间:2015-10-19 17:54:51

标签: reactjs

我在组件中使用组件。众所周知,如何将数据发送到子组件。但是,如何将值从子组件返回到父组件?我读过componentDidMountcomponentWillMount,但我仍然很难理解如何从子组件返回父组件的值。

在我的下面的代码中,请帮助我将子Catalogue.jsx中的值返回给Parent组件AppWrapper.jsx。这样,我想从Catalog.jsx中的函数ProductButtonClicked返回状态值 number_ofItems到AppWrapper.jsx 状态值 { {1}}

注意:在AppWrapper.jsx,有

这是我的Catalog.jsx文件

itemsAdded

这是我的AppWrapper.jsx

var React = require('react');
var Parse = require('parse').Parse;
var ParseReact = require('parse-react');
var cookie = require('react-cookie');

var Catalog = React.createClass({
mixins: [ParseReact.Mixin],

getInitialState: function() {
  return {
    // if the cookie is there, It will return the cookie value which I saved as 'true' word.
    FTWVeyCc4o: cookie.load('RahlTradingProductID-FTWVeyCc4o'),
    aJ3DoJp352: cookie.load('RahlTradingProductID-aJ3DoJp352'),
    dgeRhSG21U: cookie.load('RahlTradingProductID-dgeRhSG21U'),
    number_ofItems: 0
  };
},

componentDidMount: function() {
this.noOfItemsAdded();
 },


//Observe Function - a newly proposed function for prarse react integration
observe: function() {
  //declare any variable you need here.

  return {
    product: (new Parse.Query('product'))
              .ascending('createdAt')
  };
},

  //Render
  render: function() {

    var content = (
      <div>
        no product
      </div>
    );

    if(this.data.product.length){
      var content = (
        <div>
          { // Products are listed in this
                              this.data.product.map(function(p) {

                                return (
                                // <div>man</div>

                                  //From Design
                                  <div className="col-md-4">

                                      <div className="item text-center">

                                          <div className="photo">

                                              <img src={  p.productImgUrl }  />
                                              <br /><br />
                                              <h5>{p.name} <br /> {p.size}</h5>
                                          </div>
                                        </div>
                                          <div className="action">
                                              <button
                                                type="button"
                                                className={"btn btn-"
                                                  + (
                                                        (this.state.FTWVeyCc4o && (p.objectId == "FTWVeyCc4o")) || (this.state.aJ3DoJp352 && (p.objectId == "aJ3DoJp352")) || (this.state.dgeRhSG21U && (p.objectId == "dgeRhSG21U")) ? 'warning' : 'primary'
                                                    )}

                                                onClick={this.ProductButtonClicked.bind(this, p)}
                                                >
                                                {(
                                                  (this.state.FTWVeyCc4o && (p.objectId == "FTWVeyCc4o")) || (this.state.aJ3DoJp352 && (p.objectId == "aJ3DoJp352")) || (this.state.dgeRhSG21U && (p.objectId == "dgeRhSG21U")) ? 'Remove' : 'Add'
                                                )}
                                              </button>
                                              
                                          </div>


                                  </div>
                                );
                            }, this)}


        </div>

      );

    }
    else{
      var content = (<div>

      </div>);
      }
    return <div>{content}</div>;
  },

  ProductButtonClicked:function(obj){
    //alert(this.incrementCount())
    // a = this.state.bind(obj.objectId);
    // if( a == ""  )
    if( this.getCookiefunc('RahlTradingProductID-' + obj.objectId) == "")
      {
        //create the cookie
        document.cookie="RahlTradingProductID-" + obj.objectId + "=true; expires=Thu, 18 Dec 2017 12:00:00 UTC; path=/";
          //update state
          if(obj.objectId == "FTWVeyCc4o")
            {
              this.setState({FTWVeyCc4o:true});
              this.setState({number_ofItems: this.state.number_ofItems + 1});


            }
          else if(obj.objectId == "aJ3DoJp352")
            {
              this.setState({aJ3DoJp352:true});
              this.setState({number_ofItems: this.state.number_ofItems + 1});
            }
          else if(obj.objectId == "dgeRhSG21U")
            {
              this.setState({dgeRhSG21U:true});
              this.setState({number_ofItems: this.state.number_ofItems + 1});
            }
      }
    else
      {//alert("Delete Cookie")
        //delete the cookie
        document.cookie="RahlTradingProductID-" + obj.objectId + "=; expires=Thu, 18 Dec 2000 12:00:00 UTC; path=/";

        if(obj.objectId == "FTWVeyCc4o")
          {
            this.setState({FTWVeyCc4o:false});
            this.setState({number_ofItems: this.state.number_ofItems - 1});
          }
        else if(obj.objectId == "aJ3DoJp352")
          {
            this.setState({aJ3DoJp352:false});
            this.setState({number_ofItems: this.state.number_ofItems - 1});
          }
        else if(obj.objectId == "dgeRhSG21U")
          {
            this.setState({dgeRhSG21U:false});
            this.setState({number_ofItems: this.state.number_ofItems - 1});
          }

      }

  },

  noOfItemsAdded:function(){

  counter= 0;
    if(this.state.FTWVeyCc4o)
    counter = counter +1;
      if(this.state.aJ3DoJp352)
      counter = counter +1;
        if(this.state.dgeRhSG21U)
        counter = counter +1;
      this.setState({number_ofItems: counter});
      //alert(counter);
  },


  getCookiefunc:function(cname){
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
  }

});

module.exports = Catalog;

1 个答案:

答案 0 :(得分:1)

在React中,您通常会使用回调作为道具将数据传回给父级。像这样:

var Child = React.createClass({
    getDefaultProps: function() {
        return {
            onIncrementCount: null
        };
    },

    render: function() {
        return <button onClick={this.incrementCount}>Increment</button>;
    },

    incrementCount: function() {
         // Some data you want to pass externally
         var data = [1,2,3];
         this.props.onIncrementCount.call(this, data);
    }
});

var Parent = React.createClass({
    render: function() {
        return (
            <div>
                <Child onIncrementCount={this.onIncrementCount} />
                <div>Count is {this.state.count}</div>
            </div>
        );
    },

    getInitialState: function() {
        return {
            count: 0 
        };
    },

    onIncrementCount: function() {
        this.setState({count: this.state.count + 1});
    }
});

子进行回调onIncrementCount,父对象传递自己的本地函数作为回调。然后,孩子可以触发此回调。

编辑: 关于您的新信息,在ProductButtonClicked函数中,您需要将number_ofItems存储在局部变量中,然后在函数末尾指定setState。因此,不要调用setState,而是以与此类似的方式分配它:

var number_ofItems;
if( this.getCookiefunc('RahlTradingProductID-' + obj.objectId) == "")
    // Your usual logic here, but set the local variable
    number_ofItems = this.state.number_ofItems -  1;
}

// End of your function
this.setState({number_ofItems: number_ofItems});

// Send the data to the parent
this.props.incrementCount(number_ofItems);

但是,在您的父函数中,您需要在呈现时将incrementCount函数作为道具传递给Catalog。

var Parent = React.createClass({
    render: function() { 
         return <Catalog incrementCount={this.incrementCount} />;
    },

    incrementCount: function(newCount) {
        // Finally you can use your newCount here, which was from the child
    }
})