一、ref引用在DOM元素上
函数组件中的ref
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function Child (props){ let myRef =React.createRef();
const handleFocus=()=>{ myRef.current.style.borderColor="red"; } return( <div> <input type="text" ref={myRef} ></input> <input type="button" value="点我输入边框变成红色" onClick={handleFocus}/> </div> ) }
ReactDOM.render( <Child/>, document.getElementById('root') );
|
类组件中的ref
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Child extends React.Component{ constructor(props){ super(props) this.myRef =React.createRef(); }
handleFocus=()=>{ this.myRef.current.style.borderColor="red"; }
render(){ return( <div> <input type="text" ref={this.myRef} ></input> <input type="button" value="点我输入边框变成红色" onClick={this.handleFocus}/> </div> ) }
}
ReactDOM.render( <Child/>, document.getElementById('root') );
|
将ref放到函数组件和类组件的普通DOM元素上,则它们都可以获取到当前DOM元素的的原生DOM节点,就可以对这个节点进行一系列的操作。
二、ref引用在组件上
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Child extends React.Component{ constructor(props){ super(props) this.myRef =React.createRef(); }
handleFocus=()=>{ this.myRef.current.style.borderColor="red"; }
render(){ return( <div> <input type="text" ref={this.myRef} ></input> <input type="button" value="点我输入边框变成红色" onClick={this.handleFocus}/> </div> ) } }
class App extends React.Component{ constructor(props){ super(props) this.myRef =React.createRef(); } componentDidMount(){ this.myRef.current.handleFocus(); //当组件挂载时直接将输入框变成红色 } render(){ return( <Child ref={this.myRef}/> //将ref引用在Child子组件上 ) } }
ReactDOM.render( <App/>, document.getElementById('root') );
|
上面的例子在componentDidMount()方法中直接调用子组件的handleFocus(),从而实现页面一开始显示的时候输入框边框显示红色,说明在组件中引用ref,则ref指向改组件的实例,可以调用实例的方法,因为函数组件没有实例,所以函数组件不能引用ref.
另一种设置refs的方式是采用回调函数的方式, 回调函数的参数是React 组件实例或 HTML DOM 元素 ,ref指向哪一个DOM元素或者组件由这个回调函数决定。
!!!!!!!!!注意!!!!!!!
使用回调函数的方式设置refs 时,在访问DOM节点的时候不需要用current属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Child extends React.Component{ constructor(props){ super(props) this.myRef = null
this.setMyRef = (input)=>{ this.myRef = input; }
}
handleFocus=()=>{ console.log(this.myRef); this.myRef.style.borderColor="red"; }
render(){ return( <div> <input type="text" ref={this.setMyRef} ></input> <input type="button" value="点我输入边框变成红色" onClick={this.handleFocus}/> </div> ) } }
|