在某个class类组件里面有一个方法,其他的组件中也需要,粘贴复制太low了,并且大大增加代码量,我想用导入导出的方法拿取到里面的方法,有大佬能告诉我吗
在某个class类组件里面有一个方法,其他的组件中也需要,粘贴复制太low了,并且大大增加代码量,我想用导入导出的方法拿取到里面的方法,有大佬能告诉我吗
方法1:使用 ref 可以获取到组件 绑定到this 上的方法
// Video.js
class Video extends Component {
...
play = () => {
this.setState({ isPlay: true })
}
}
// page.js
...
class Page extends Component {
videoInstance = null
handlePlay = () => {
// 调用某个组件内部函数
this.videoInstance.play()
}
render() {
return <Video ref={(ref) => this.videoInstance = ref} />
}
}
....
方法2:将复用部分抽象成高阶组件
function playHOC(WrappedComponent) {
return class Play extends React.Component {
play = () => {
do something...
}
render() {
return <WrappedComponent {...this.props} play={this.play} />
}
}
}
// 页面中
class Page extends Component {
handlePlay =() => {
// 调用高阶组件中的方法
this.props.play()
}
}
playHOC(<Page>)
方法4: 定义 static 方法 缺点是无法访问this
方法3: hook 最推荐
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答5.2k 阅读✓ 已解决
1 回答3.3k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
可以把这个方法放到class上面用export导出,但是这样肯定不妥。 你应该把这个方法单独放到一个js文件里再分别导入。