简体   繁体   English

如何将 ref 设置为未渲染的元素

[英]How to set ref to an unrendered element

I have a login page where I'm placing a button "Watch the video".我有一个登录页面,我在其中放置了一个“观看视频”按钮。 On click of the button, I'm hiding the button and displaying a video.单击按钮后,我将隐藏按钮并显示视频。 Now my requirement is to start playing the video as soon as it displays without having to click the play button.现在我的要求是在视频显示后立即开始播放,而无需单击播放按钮。 I'm trying to use refs and somehow I'm unable to set the ref to my video element.我正在尝试使用 refs,但不知何故我无法将 ref 设置为我的视频元素。 Is there any way to set the refs to unrendered elements in componentDidUpdate?有什么方法可以将 refs 设置为 componentDidUpdate 中未渲染的元素? Please help me!请帮我! Following is my code以下是我的代码

export default class NewLoginPage extends Component {
  constructor(props) {
    this.vidRef = React.createRef();
    this.state = {
      showVideo: false
    };
  }
    
  handleVideoClick = () => {
    this.setState({ showVideo: true })
    this.vidRef.current.play();
  }
    
  handleCloseClick = () =>{
    this.setState({ showVideo: false })
  }
    
  render() {
    let language_labels = labels["english_labels"]
    console.log(labels)
    console.log(language_labels)
    return (
      <div className="container-fluid no-padding">
        <div className="new-login-div">
          <AppBar className="app-bar">
            <Toolbar className="tool-bar">
              <img src={pmiLogo} />
              {/* <NavLink to="/" id="invoice_upload">LOG OUT</NavLink> */}
              {/* <Button className="logout-btn">REGISTER</Button> */}
            </Toolbar>
          </AppBar>
          <Grid container>
            <Grid item xs={4}>
              <h1 className="welcome-heading">Self Service Portal</h1>
              <TextField
                className="id-field"
                placeholder="Email"
                inputProps={{
                  style: {
                    color: "#fff",
                    paddingLeft: "5px"
                  }
                }}
              />
              <br />
              <Button className="login-btn" endIcon={<ArrowForwardIcon />}>Log In</Button>
            </Grid>
            <Grid item xs={8}>
              <div className="video-div">
                {this.state.showVideo && <div>
                 <IconButton className="close-btn" onClick={(event) => this.handleCloseClick()}>
                   <CloseIcon />
                 </IconButton>
                 <video ref={ref => { this.vidRef = ref }} width="500" height="285" controls className="video-container">
                   <source src={exampleVid} type="video/mp4" />
                   Your browser does not support the video tag.
                 </video>
               </div>}
               {!this.state.showVideo && <div className="intro-div">
                 <h5 className="intro-text">
                   Supporting the vitality and survival of US small businesses—who employ nearly half of the American workforce—is especially critical now. Let’s not forget just how essential they are.
                 </h5>
                 <Button
                   disableRipple={true}
                   className="video-button"
                   startIcon={<PlayArrowIcon className="play-icon" />}
                   onClick={(event) => this.handleVideoClick()}
                 >
                   Watch video
                 </Button>
                 <br />
                 <Button
                   disableRipple={true}
                   className="reg-button"
                   startIcon={<ChevronRightIcon className="play-icon" />}>
                   Register
                 </Button>
               </div>}
             </div>
           </Grid>
         </Grid>
       </div>
     </div>
   );
  }
}

React ref property is used to access DOM element reference. React ref 属性用于访问 DOM 元素引用。
If element is not rendered then DOM element is not created (deleted).如果元素未呈现,则不会创建(删除)DOM 元素。
Thus you can't get a ref of something that doesn't exist.因此,您无法获得不存在的东西的参考。

You don't need to use a ref to do that, you can add the autoplay html property to your <video> for details on autoplay您不需要使用 ref 来执行此操作,您可以将autoplay html 属性添加到您的<video>以获取有关自动播放的详细信息

You can't make use of a ref to an element that is not yet rendered as Anton explained in his answer , the ref.current will be null.您不能像 Anton 在他的回答中解释的那样对尚未呈现的元素使用 ref, ref.current将为空。

However, it is suggested that you create a separate component for the video and it's logic from that of the login , not only it will solve the issue (the this.state.showVideo condition will stay in the parent component) but it is also how React components should be, for more details refer to this .但是,建议您为video创建一个单独的组件,它的逻辑与login的逻辑相同,不仅可以解决问题( this.state.showVideo条件将保留在父组件中),而且还可以解决问题React 组件应该是,更多细节参考这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM