ReactJS中的子父组件通信 [英] Child parent component communication in ReactJS
本文介绍了ReactJS中的子父组件通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我喜欢在事件fire onDrag
上将子属性的属性/ props / state值从子组件发送到父组件。我找不到合适的文件。
I like to send the attribute properties/props/state values from child component to parent component on an event fire onDrag
. I could not find proper documentation on this.
这是我的代码:
/*** @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);
我希望我的代码清晰。
推荐答案
在App组件中这一行
<videos handle={this.handleDrag(vidurl)} />
不正确,应该传递函数回调而不是调用函数。
is not correct, one should pass the function callback instead of invoke a function.
在VideoForm中这一行
In VideoForm this line
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)
is not correct, this.props.handle is the parent callback, one should just just call 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
}
});
这篇关于ReactJS中的子父组件通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文