React: onRef 和 ref

本文详细探讨了React中的onRef和ref特性。onRef主要用于实现父组件获取子组件的实例,而ref则能获取到组件的真实DOM或者类组件的实例。在原生组件上,ref的current属性将返回DOM节点;对于类组件,它返回组件实例。需要注意的是,函数组件无法使用ref。此外,ref保存的引用在变化时不会触发重新渲染,适用于保存如非受控组件或计时器实例等不涉及页面渲染的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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保存的数据更改时不会触发重新渲染,适合用来保存如非受控组件、计时器实例等不关联页面渲染操作的可变引用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值