I had a really weird bug in my application where an <iframe> wasn't loading if it was added to the DOM by hitting ESCAPE.
class App extends React.Component {
constructor() {
super()
this.state = { toggled: true }
this.toggle = this.toggle.bind(this)
}
componentDidMount() {
document.addEventListener('keydown', (e) => {
if (e.keyCode === 27) {
// Uncomment the next line to make the video work when hitting ESC
// e.preventDefault()
this.setState({ toggled: false })
}
})
}
toggle() {
this.setState({ toggled: !this.state.toggled })
}
render() {
return (
<div>
{this.state.toggled
? <div>Hit ESC to show the video</div>
: (
<div>
<div><button onClick={this.toggle}>Hide video</button></div>
<iframe width="560" height="315" src="https://www.youtube.com/embed/lUOK2ZpjvaM" frameborder="0"></iframe>
</div>
)
}
</div>
)
}
}
What you're seeing here is a simple React app that shows an embedded YouTube-Video when you hit ESCAPE. There is something I don't understand about this though: The <iframe> only loads if I preventDefault() on the keydown event.
Why is this necessary? I've observed this behaviour in Chrome and Firefox.
Aucun commentaire:
Enregistrer un commentaire