【发布时间】:2018-11-18 19:14:33
【问题描述】:
我在我的应用程序中使用Expo's Video component,它使用 ref 方法来处理视频的状态。
我需要其他组件能够调用 .playAsync() 和 .pauseAsync() 等方法,而无需将它们作为道具传递。
是否可以通过调度 redux 操作来调用这些方法?
【问题讨论】:
标签: reactjs react-native redux react-redux expo
我在我的应用程序中使用Expo's Video component,它使用 ref 方法来处理视频的状态。
我需要其他组件能够调用 .playAsync() 和 .pauseAsync() 等方法,而无需将它们作为道具传递。
是否可以通过调度 redux 操作来调用这些方法?
【问题讨论】:
标签: reactjs react-native redux react-redux expo
我不经常使用 ref,我不太喜欢它,reactjs 的文档显示了为什么这不是最好的方法。我真的建议您先阅读此内容https://reactjs.org/docs/refs-and-the-dom.html。但有时你别无选择。如果你真的想使用它。你可以这样做 :) 希望这对你来说是一个很好的例子 :)
// VideoService.js
let _video;
function setVideo(videoRef) {
_video = videoRef
};
function play() {
return _video.playAsync();
}
function pause() {
return _video.pauseAsync()
}
export const VideoService = {
setVideo,
play,
pause
}
// YouCp.js
import { VideoService } from './VideoService';
class YourCp extends Component {
state = { }
render() {
return (
<Video ref={r => VideoService.setVideo(r)} />
);
}
}
export default YourCp;
// actions.js
import { VideoService } from './VideoService';
export const play = () => async dispatch => {
await VideoService.play()
// other logic
}
【讨论】:
所以,我不确定您的确切用例,但我相当肯定在反应中像这样传递引用并不是一个好习惯。您真的应该将 updateThisComp 函数传递到您需要操作视频的任何地方。
https://reactjs.org/docs/refs-and-the-dom.html
您应该添加一个方法或操作,通过传递这些 .playAsync 等来更新视频所在的组件状态...
它可能看起来像这样。
const updateVideoState = (actionType) => {
actionType === 'pause' ? 'updateYourReduxStoreVideoState' : undefined
// change updateYourReduxStoreVideoState === true || false
}
然后在您的视频组件中...
<SomeVideoPackage pause={this.props.reduxStoreVideoStatePause} />
// this.props.reduxStoreVideoStatePause === true || false
或者....
componentDidMount(){
this.props.reduxStoreVideoStatePause ? this.referenceName.pauseAsync()
}
【讨论】: