25 Refs转发机制与在高阶组件中的使用
生活随笔
收集整理的這篇文章主要介紹了
25 Refs转发机制与在高阶组件中的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
將子節點的ref暴露給父節點
- 16.3以上 Refs轉發,將ref自動通過組件傳遞給子組件
在高階組件中轉發
- 匿名改具名
16.2及以下 Refs轉發
1. props傳遞
class MyInput extends React.Component {render() {return (<input type="text" ref={this.props.inputRef} placeholder={this.props.placeholder} />)} } class App extends React.Component {constructor(props) {super(props)this.refInApp = React.createRef()}componentDidMount() {console.log('【APP】componentDidMount', this.refInApp)}inputOperate = () => {const oInput = this.refInApp.currentoInput.focus()}render() {return (<>{/* 用ref接收轉發的ref */}<MyInput inputRef={this.refInApp} placeholder="請輸入" /><button onClick={this.inputOperate}>聚焦</button></>)} } ReactDOM.render(<App />,document.getElementById('app') )2. 回調
class MyInput2 extends React.Component {constructor(props) {super(props)this.innerInput = null}setMyInput = (el) => {// 這里就是dom,沒有包裹在對象里console.log('回調的方式el', el)this.innerInput = el;}inputOperate = () => {this.innerInput.value = ''this.innerInput.focus()}render() {return (<><input type="text" ref={this.setMyInput} /><button onClick={this.inputOperate}>聚焦(回調方式)</button></>)} }3. 在父組件回調
class MyInput3 extends React.Component {render() {return (<input type="text" ref={this.props.inputRef} />)} } class App extends React.Component {componentDidMount() {// 在父組件獲取到子組件的dom,不是包裹在對象里的console.log('【APP】componentDidMount', this.oInput)}inputOperate2 = () => {this.oInput.focus()}render() {return (<><MyInput3 inputRef={el => this.oInput = el} /><button onClick={this.inputOperate2}>聚焦(回調2,定義在父組件) </button></>)} }4. 字符串形式 已廢棄
- 依賴組件實例下面的refs集合里的ref
- 需要React保持追蹤當前正在渲染的組件(沒有加載完成,this沒法確定)
- 可能會比較慢
- 不能在render中工作
- 不能組合,只能有一個ref屬性
總結
以上是生活随笔為你收集整理的25 Refs转发机制与在高阶组件中的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1360E. Polygon
- 下一篇: 我的大学生涯软件工程一年半