onRef
实现父组件获取子组件实例
class Parent extends Component{
childFunc(){
if(this.child){ // 判断this.child值
// this.child 指向 子组件实例
// 调用子组件方法
this.child.func('123')
console.log('父组件调用子组件方法')
}
}
bindChild(child){
// 接收子组件实例,指向this.child
this.child = child
}
render(){
return(
<div onClick={this.childFunc}> // 点击尝试调用子组件方法
// 通过onRef属性将引用子组件实例方法传给子组件
<Child onRef={this.bindChild}></ChildPage>
</div>
)
}
}
class Child extends Component{
constructor(props){
super(props)
this.state = '000'
if(props.onRef){
// 如果接收到onRef方法,则调用该方法并传入子组件this指针
// 子组件this指针被挂载到父组件this.child上
props.onRef(this)
}
}
func = arg => {
setState(arg)
}
render(){
return <span>{this.state}<span>
}
}
ref
获取组件真实DOM
// 类组件
class NameForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
// 使用React.createRef方法来创建ref
this.inputRef = React.createRef();
}
handleSubmit(event) {
// 通过ref的current属性获取真实DOM
alert(this.inputRef.current.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
// 通过组件ref属性将组件的真实DOM引用添加到this.inputRef
<input type="text" ref={this.inputRef} /> // input 为 非受控组件
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
// 函数组件
function NameForm(props) {
// 使用useRef方法来创建ref
const inputRef = useRef(null);
function handleSubmit(event) {
// 通过ref的current属性获取真实DOM
alert(inputRef.current.value);
event.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
// 通过组件ref属性将组件的真实DOM引用添加到this.inputRef
<input type="text" ref={inputRef} /> // input 为 非受控组件
</label>
<input type="submit" value="Submit" />
</form>
);
}
ref 的值根据节点的类型而有所不同:
- 当 ref 属性用于原生组件时, ref 接收组件的真实DOM 作为其 current 属性。
- 当 ref 属性用于类组件时,ref 接收组件实例作为其 current 属性。
- 函数组件没有实例,不能使用 ref 属性。
通过ref保存的数据更改时不会触发重新渲染,适合用来保存如非受控组件、计时器实例等不关联页面渲染操作的可变引用。