【问题标题】:Child parent component communication in ReactJSReactJS 中的子父组件通信
【发布时间】:2015-03-18 12:22:14
【问题描述】:

我喜欢在事件触发onDrag 时将属性属性/道具/状态值从子组件发送到父组件。我找不到这方面的适当文档。

这是我的代码:

/*** @jsx React.DOM */
var APP=React.createClass({
  getInitialState:function()
  {
     return {url:'http://www.youtube.com/embed/XGSy3_Czz8k'}
  },
  handleDrag:function(vidurl)
  {
    alert(vidurl);    //i need to get child component url here.
  },
  render:function(){
    return  <div>
               <VideoFrame  src={this.state.url} />
               <hr/>
           <videos handle={this.handleDrag(vidurl)} />
        </div>
  }
});

var VideoFrame=React.createClass({
  render:function(){
    return  <div>
          <iframe width="420" height="315"  src={this.props.src}>
          </iframe>     
        </div>
  }
});

var videos=React.createClass({
  getInitialState:function()
  {
    return {vidurl:'http://www.youtube.com/embed/XGSy3_Czz8k'}
  },
  render:function()
  {
    return  <img src="http://upload.wikimedia.org/wikipedia/en/a/a6/Size_Small.PNG" onDrag={this.props.handle.bind(this.state.vidurl)}></img> //trying to send state value from here
  }
});

React.renderComponent(<APP />, document.body);      

我希望我的代码是清晰的。

【问题讨论】:

标签: javascript reactjs react-jsx reactjs-native


【解决方案1】:

在 App 组件中这一行

<videos handle={this.handleDrag(vidurl)} />

不正确,应该传递函数回调而不是调用函数。

在 VideoForm 中这一行

return  <img src="http://upload.wikimedia.org/wikipedia/en/a/a6/Size_Small.PNG" onDrag={this.props.handle.bind(this.state.vidurl)}></img> //trying to send state value from here

不正确,this.props.handle 是父回调,应该只是调用 this.props.handle(this.state.videoUrl)

正确的实现:

var APP = React.createClass({
  getInitialState:function() {
   return {url:'http://www.youtube.com/embed/XGSy3_Czz8k'}
  },

  // Parent callback, pass this function to the child component
  handleDrag:function(videoUrl) {
    alert(videoUrl);
  },

  render: function() {
    return  (
      <div>
         <Videos handle={this.handleDrag} />
      </div>
    );
})


var Videos = React.createClass({

  getInitialState:function()
  {
    return {vidurl:'http://www.youtube.com/embed/XGSy3_Czz8k'}
  },

  handleChanged: function(event) {
    if(this.props.handle) {
      this.props.handle(this.state.videoUrl);
    }
  },

  render:function()
  {
    return  <img src="http://upload.wikimedia.org/wikipedia/en/a/a6/Size_Small.PNG" onDrag={this.handleChanged}></img> //trying to send state value from here
  }
});

【讨论】:

    【解决方案2】:

    bind的第一个参数是调用绑定方法时设置为“this”的对象,bind的第二个参数是传入的第一个参数。

    确保也传递函数,在第一个类中调用 handleDrag 然后将返回值传递给视频组件,而不是传入 handleDrag 本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 2019-03-19
      • 2017-03-03
      • 2023-03-06
      相关资源
      最近更新 更多