【问题标题】:How to access ref from another component using React and Redux?如何使用 React 和 Redux 从另一个组件访问 ref?
【发布时间】:2018-11-18 19:14:33
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

    我不经常使用 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
    }
    

    【讨论】:

      【解决方案2】:

      所以,我不确定您的确切用例,但我相当肯定在反应中像这样传递引用并不是一个好习惯。您真的应该将 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()
      }
      

      【讨论】:

        猜你喜欢
        • 2020-04-28
        • 1970-01-01
        • 2017-04-02
        • 1970-01-01
        • 1970-01-01
        • 2018-02-09
        • 2018-01-03
        • 2023-03-30
        • 2019-05-17
        相关资源
        最近更新 更多