23 Refs的应用场景与选用思考
生活随笔
收集整理的這篇文章主要介紹了
23 Refs的应用场景与选用思考
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Refs含義
- 允許訪問真實DOM
- React數據流:通過props來實現父子組件的交互
- Refs允許強制修改子組件
input
class MyInput extends React.Component {constructor(props) {super(props)this.inputRef = React.createRef()}state = {value: '123'}// 聚焦 失焦inputFocus = () => {const oInput = this.inputRef.currentoInput.focus()oInput.value = ''}inputBlur = () => {const oInput = this.inputRef.currentoInput.blur()oInput.value = ''}changeInputValue = (e) => {this.setState({value: e.target.value})}render() {return (<div><inputtype="text"ref={this.inputRef}value={this.state.value}onChange={this.changeInputValue}/><button onClick={this.inputFocus}>聚焦</button><button onClick={this.inputBlur}>失焦</button></div>)} }video
class MyVideo extends React.Component {constructor(props) {super(props);this.videoRef = React.createRef();}videoPlay = (operation) => {const oVideo = this.videoRef.currentoperation === 'play' ? oVideo.play() : oVideo.pause()}render() {return (<div><video src="https://www.w3school.com.cn/i/movie.ogg"width="300"height="200"controlsref={this.videoRef}></video><div><button onClick={() => this.videoPlay('play')}>播放</button><button onClick={() => this.videoPlay('pause')}>暫停</button></div></div>)} }強制動畫
class MyBox extends React.Component {constructor(props) {super(props)this.boxRef = React.createRef()}growBox = () => {const oBox = this.boxRef.currentoBox.style.width = '400px'oBox.style.height = '400px'oBox.style.backgroundColor = 'skyblue'}render() {return (<><divstyle={{width: 200 + 'px',height: 200 + 'px',backgroundColor: 'orange',transition: 'all 1s'}}ref={this.boxRef}></div><button onClick={this.growBox}>變大</button></>)} }引入jQuery
growBox = () => {const $box = $(this.boxRef.current)console.log('jquery dom對象', $box)$box.animate({width: '400px',height: '400px',})}模態框 狀態提升
class Modal extends React.Component {constructor(props) {super(props)this.modalRef = React.createRef()}render() {return (<divref={this.modalRef}style={{width: '300px',border: '1px solid #000',display: this.props.toOpen ? 'block' : 'none'}}><h1>This is a Modal</h1><p>This is a super Modal</p></div>)} } class App extends React.Component {state = {toOpen: false,}changeStatus = (toOpen) => {this.setState({toOpen})}render() {return (<><Modal toOpen={this.state.toOpen} /><button onClick={() => this.changeStatus(true)}>打開</button><button onClick={() => this.changeStatus(false)}>關閉</button></>)} }總結
以上是生活随笔為你收集整理的23 Refs的应用场景与选用思考的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql常用命令英文词汇_MySQL中
- 下一篇: 24 React.createRef()