forwardRef
引用传递(Ref forwading)是一种通过组件向子组件自动传递 引用ref 的技术。对于应用者的大多数组件来说没什么作用。但是对于有些重复使用的组件,可能有用。例如某些input组件,需要控制其focus,本来是可以使用ref来控制,但是因为该input已被包裹在组件中,这时就需要使用Ref forward来透过组件获得该input的引用。可以透传多层
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import React, {Component, forwardRef} from 'react';
class App extends Component { mytext = React.createRef() render() { return ( <div> <button onClick={() => { this.mytext.current.focus() this.mytext.current.value = '' }}>获取焦点</button> <Child ref={this.mytext} /> </div> ); } } const Child = forwardRef((props,ref) => { return <div style={{background:'red'}}> <input defaultValue={222} ref={ref} type="text"/> </div> }) export default App;
|