reactjs - 如何使用 React 和 Redux 访问另一个组件的 ref?

标签 reactjs react-native redux react-redux expo

我正在使用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/

相关文章:

javascript - Reactjs 与 Laravel REST API : No 'Access-Control-Allow-Origin' header is present on the requested resource

javascript - React中组件之间的数据传输

session - 异步存储 : React Native

javascript - React-native 变量与状态

javascript - 使用 redux-thunk 连接 action creators、reducers 时,数据未出现在组件中

javascript - react-testing-library getAll 然后过滤找到一个元素

javascript - Radium 内联 CSS - 构建导出类?

reactjs - 更新状态的多个部分的 Reducer

javascript - 异步调用 axios API 后使用 React hook 和 redux 设置状态

javascript - ngrx/redux 操作上下文的最佳实践