html - 如何将 ref 设置为未渲染的元素
问题描述
我有一个登录页面,其中放置了一个“观看视频”按钮。单击按钮后,我将隐藏按钮并显示视频。现在我的要求是在视频显示后立即开始播放,而无需单击播放按钮。我正在尝试使用 refs,但不知何故我无法将 ref 设置为我的视频元素。有没有办法将 refs 设置为 componentDidUpdate 中未渲染的元素?请帮我!以下是我的代码
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 属性用于访问 DOM 元素引用。
如果未渲染元素,则不会创建(删除)DOM 元素。
因此,您无法获得不存在的东西的参考。
推荐阅读
- ios - MGLMapView - Mapbox 注释崩溃
- python - 如何从数据框中的列中替换值/字符串?
- c# - 保存工作簿时无法访问已关闭的文件
- angular - @angular/cli 6.0 tslint teamcity 格式不再起作用
- python - 日期之间的 Instagram 图形 API 媒体帖子
- autofac - Service Fabric Autofac如何?
- vba - 从另一个工作表中查找值(循环中的循环)
- python - Postgres - 如何在 Windows 上使用 psql 从 Python 执行多行查询?
- javascript - 使用 startAt 进行 Firebase 查询
- json - Json 结果显示时显示错误的值