日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

23 Refs的应用场景与选用思考

發布時間:2023/12/10 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 23 Refs的应用场景与选用思考 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Refs含義

  • 允許訪問真實DOM
  • React數據流:通過props來實現父子組件的交互
  • Refs允許強制修改子組件
// 1. 構造器離添加實例屬性 this.ref = React.createRef() // 2. 組件上綁定ref ref={this.ref} // 3. 使用:this.ref.current

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的应用场景与选用思考的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。