ReactJS中的子-父组件通信
Child parent component communication in ReactJS
我喜欢在事件触发onDrag
时将属性props/state值从子组件发送到父组件。我找不到有关这方面的适当文件。
这是我的代码:
/*** @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);
我希望我的代码是清晰的。
在应用程序组件中,此行
<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
}
});
要绑定的第一个参数是调用绑定方法时要设置为"this"的对象,要绑定的第二个参数是传入的第一个自变量。
请确保也传递函数,在第一个类中,您将调用handleDrag,然后将返回值传递到视频组件,而不是传递handleDrag本身。
相关文章:
- Ember.js:接受的子组件和父组件之间通信的最佳实践
- ReactJS中的子-父组件通信
- 我应该如何在 React 中与我的组件进行通信
- 通过返回键进行跨组件通信
- 角度1.5中的组件通信
- React组件与Native Mobile(iOS或Android)的通信
- Vuejs中同级组件之间的通信
- 角度 2 同级组件通信
- 角度 2 交叉应用程序(根组件)通信
- Reactjs 组件之间的通信
- AngularJS:在组件之间进行通信的最佳实践是什么?
- React 同级组件在按下按钮时进行通信(登录表单)
- Mithril js - 跨组件通信模式
- 如何管理独立反应组件之间的通信
- 在不使用状态/属性的情况下与父组件通信
- Vue组件通信
- AngularJS 2:如何拥有一个'属性'指令与其主机组件通信
- ReactJS组件通信
- 主干视图-跨组件通信
- Angularjs 1.5 -使用service的组件通信-异步变量操作