reactjs组件之间的传值

来源:互联网 发布:mac怎么下载skype 编辑:程序博客网 时间:2024/06/05 04:54

1、父组件向子组件传值

// 父组件var MyContainer = React.createClass({  render: function() {    return (      <Intermediate text="where is my son?" />    );  }});// 子组件1:中间嵌套的组件var Intermediate = React.createClass({  render: function () {    return (      <Child text={this.props.text} />    );  }});// 子组件2:子组件1的子组件var Child = React.createClass({  render: function () {    return (      <span>{this.props.text}</span>    );  }});

2、子组件向父组件传值

// 父组件var MyContainer = React.createClass({  getInitialState: function () {    return {      totalChecked: 0    };  },  onChildChanged: function (newState) {    var newToral = this.state.totalChecked + (newState ? 1 : -1);    this.setState({      totalChecked: newToral    });  },  render: function() {    var totalChecked = this.state.totalChecked;    return (      <div>        <div>How many are checked: {totalChecked}</div>        <ToggleButton text="Toggle me"          initialChecked={this.state.checked}          callbackParent={this.onChildChanged}          />        <ToggleButton text="Toggle me too"            initialChecked={this.state.checked}            callbackParent={this.onChildChanged}          />        <ToggleButton text="And me"          initialChecked={this.state.checked}          callbackParent={this.onChildChanged}          />      </div>    );  }});// 子组件var ToggleButton = React.createClass({  getInitialState: function () {    return {      checked: this.props.initialChecked    };  },  onTextChange: function () {    var newState = !this.state.checked;    this.setState({      checked: newState    });    // 这里要注意:setState 是一个异步方法,所以需要操作缓存的当前值    this.props.callbackParent(newState);  },  render: function () {    // 从【父组件】获取的值    var text = this.props.text;    // 组件自身的状态数据    var checked = this.state.checked;    return (        <label>{text}: <input type="checkbox" checked={checked} onChange={this.onTextChange} /></label>    );  }});
3、兄弟组件互相传值:

// 定义一个容器var ProductList = React.createClass({    render: function () {      return (        <div>          <ProductSelection />          <Product name="product 1" />          <Product name="product 2" />          <Product name="product 3" />        </div>      );    }});// 用于展示点击的产品信息容器var ProductSelection = React.createClass({  getInitialState: function() {    return {      selection: 'none'    };  },  componentDidMount: function () {    this.pubsub_token = PubSub.subscribe('products', function (topic, product) {      this.setState({        selection: product      });    }.bind(this));  },  componentWillUnmount: function () {    PubSub.unsubscribe(this.pubsub_token);  },  render: function () {    return (      <p>You have selected the product : {this.state.selection}</p>    );  }});var Product = React.createClass({  onclick: function () {    PubSub.publish('products', this.props.name);  },  render: function() {    return <div onClick={this.onclick}>{this.props.name}</div>;  }});




原创粉丝点击