我喜欢在事件fire上将属性properties / props / state值从子组件发送到父组件onDrag。我找不到关于此的适当文档。
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);
我希望我的代码清楚。
在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 } });