我正在使用Expo's Video component在我的应用程序上,它使用 ref 方法来处理视频的状态。
我需要其他组件能够调用 .playAsync()
和 .pauseAsync()
等方法,而无需将它们作为 props 传递下来。
是否可以通过调度 redux 操作来调用这些方法?
最佳答案
我不经常使用 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
}
关于reactjs - 如何使用 React 和 Redux 访问另一个组件的 ref?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50765503/