【发布时间】:2016-04-12 10:23:11
【问题描述】:
我在 React 中制作了一个小的 Video 组件(你猜对了,播放视频),我想将该组件嵌入到父组件中,然后能够在视频组件上调用 play 方法.
我的视频组件看起来像:
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
const { string, func } = PropTypes;
export default class Video extends Component {
static propTypes = {
source: string.isRequired,
type: string.isRequired,
className: string
};
play = () => {
};
render = () => {
const { className } = this.props;
return (
<video className={ className } width="0" height="0" preload="metadata">
<source src={ this.props.source } type={ this.type } />
Your browser does not support the video tag.
</video>
);
};
}
这真的很简单,这里没什么特别的。
现在在父组件中,我们称之为Page:
export default class Page extends Component {
video = (
<Video source="some_url" type="video/mp4" />
);
render = () => {
<div onClick={ this.video.play } />
}
}
但是,如果我登录 .play,它是未定义的。
接下来我尝试将play 声明为Video 中的道具并放置一个默认道具,例如:
static defaultProps = {
play: () => {
const node = ReactDOM.findDOMNode(this);
}
}
但在这种情况下,this 未定义。
在 React ES6 类上公开函数以便外部组件调用它的正确方法是什么?我应该在Video.prototype 上附加一些东西吗?
【问题讨论】:
标签: javascript html reactjs ecmascript-6