【问题标题】:ReactJS - how to pass component reference to another component as prop?ReactJS - 如何将组件引用作为道具传递给另一个组件?
【发布时间】:2019-04-14 14:28:47
【问题描述】:

我有两个兄弟组件WebcamStreamCaptureArea,我想将WebcamStream 的引用作为CaptureArea 的属性传递,但是当我这样做时,它总是为空。如何解决这个问题?

class AppContent extends React.Component {
    constructor(props) {
        super(props);
        this.videoTag = React.createRef();
    }

    render() {
        return (
            <div id="content">
                <WebcamStream ref={this.videoTag}
                              width="300" height="300" 
                              title="Real-time video stream from webcam" 
                              id="video" />
                <CaptureArea x="20" y="20" width="120" 
                             height="120" color="white" 
                             videoTag={this.videoTag.current}/>
            </div>
        );
    }
}

我为什么需要这个: CaptureArea 在当前的 video 标签上生成临时画布,以从中获取 imageData。我使用 imageData 来解析二维码。

【问题讨论】:

    标签: reactjs react-ref


    【解决方案1】:

    ref 是 React 内部使用的一个 prop,很像 key prop,因此您可以将其命名为其他名称,并将其视为 WebcamStream 组件中的任何其他 prop。

    innerRef 是您附加到组件中任何元素的自定义 ref 的通用名称。

    示例

    function WebcamStream(props) {
      return <div ref={props.innerRef}> WebcamStream </div>;
    }
    
    class CaptureArea extends React.Component {
      componentDidMount() {
        console.log(this.props.videoTag.current);
      }
      render() {
        return <div> CaptureArea </div>;
      }
    }
    
    class AppContent extends React.Component {
      videoTag = React.createRef();
    
      render() {
        return (
          <div id="content">
            <WebcamStream
              innerRef={this.videoTag}
              width="300"
              height="300"
              title="Real-time video stream from webcam"
              id="video"
            />
            <CaptureArea
              x="20"
              y="20"
              width="120"
              height="120"
              color="white"
              videoTag={this.videoTag}
            />
          </div>
        );
      }
    }
    
    ReactDOM.render(<AppContent />, document.getElementById("root"));
    <script src="https://unpkg.com/react@16.6.1/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@16.6.1/umd/react-dom.production.min.js"></script>
    
    <div id="root"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      相关资源
      最近更新 更多