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

时间:2018-06-08 17:10:33

标签: reactjs react-native redux react-redux expo

我在我的应用程序上使用Expo's Video component,它使用ref方法来处理视频的状态。

我需要其他组件才能调用.playAsync().pauseAsync()等方法,而不将其作为道具传递。

是否可以通过调度redux操作来调用这些方法?

2 个答案:

答案 0 :(得分:0)

所以,我不确定你的确切使用案例,但我相当确定将反应中的参考传递下来并不是一个好习惯。你真的应该将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()
}

答案 1 :(得分:0)

我不使用ref很多原因,我不喜欢它,反应的文档显示为什么这不是最好的方法。我真的建议你先阅读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
}