为什么不提醒(“onEnded”)有效?就像在手册上做的一样。
如何在PlayerContainer中启动它?
var PLAYER_ID = 'player';
var Player = React.createClass({
componentDidMount: function() {
document.getElementById(PLAYER_ID).addEventListener( 'ended', this.onEnded )
},
componentWillUnmount: function() {
document.getElementById(PLAYER_ID).removeEventListener( 'ended', this.onEnded )
},
render: function () {
return (
<video
id={PLAYER_ID}
src={this.props.src}
</video>
)
}
});
var PlayerContainer = React.createClass({
onEnded: function () {
alert("onEnded")
},
render: function() {
return <Player
src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"/>
}
});
React.render(
<PlayerContainer />,
document.body
);
如何解决?
抱歉这个愚蠢的问题。我学习React.js
答案 0 :(得分:0)
this
中的{p> this.onEnded
引用Player
个实例而不是PlayerContainer
个实例,Player
没有onEnded
方法,请尝试这样:
var PLAYER_ID = 'player';
var Player = React.createClass({
componentDidMount: function() {
document.getElementById(PLAYER_ID).addEventListener( 'ended', this.props.onEnded )
},
componentWillUnmount: function() {
document.getElementById(PLAYER_ID).removeEventListener( 'ended', this.props.onEnded )
},
render: function () {
return (
<video
id={PLAYER_ID}
src={this.props.src}
</video>
)
}
});
var PlayerContainer = React.createClass({
onEnded: function () {
alert("onEnded")
},
render: function() {
return <Player
src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
onEnded={this.onEnded}/>
}
});
React.render(
<PlayerContainer />,
document.body
);
&#13;
答案 1 :(得分:0)
创建反应应用时,您应该避免自己访问DOM。 React为html元素上的事件提供回调。您需要通过props将回调传递给video
组件:
var Player = React.createClass({
render: function () {
return (
<video
id={PLAYER_ID}
src={this.props.src}
// pass the callback provided in the props to your video element
onEnded={this.props.onEnded}
/>
)
}
});
var PlayerContainer = React.createClass({
onEnded: function () {
alert("onEnded")
},
render: function() {
return (
<Player
src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
// pass the callback to your Player component so that it will have it in it's props
onEnded={this.onEnded}
/>
);
}
});
React.render(
<PlayerContainer />,
document.body
);
此外,如果您是新手,我建议您使用ES6语法,并执行也使用ES6的very good tutorial。
ES6语法中的相同组件:
import React, {Component} from 'react';
const Player = ({src, onEnded}) => (
<video src={src} onEnded={onEnded} />
);
class PlayerContainer extends Component {
onEnded = () => {
alert("onEnded");
}
render() {
return (
<Player
src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
onEnded={this.onEnded}
/>
);
}
}
React.render(
<PlayerContainer />,
document.body
);
提示:<video>
元素没有正文。
答案 2 :(得分:0)
您必须将onEnded
作为道具从PlayerContainer
传递到Player
,因此在PlayerContainer
中您必须拨打this.props.onEnded
而不是this.onEnded
}
我重现了这个场景,请查看: