Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[React] ref 有哪些使用场景,请举例【热度: 668】 #477

Open
yanlele opened this issue Jul 9, 2023 · 0 comments
Open

[React] ref 有哪些使用场景,请举例【热度: 668】 #477

yanlele opened this issue Jul 9, 2023 · 0 comments
Labels
web框架 web 框架相关知识 美团 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Jul 9, 2023

关键词:ref 使用场景、ref 获取dom、ref 获取子组件属性和方法

React的ref用于获取组件或DOM元素的引用。它有以下几个常见的使用场景:

  1. 访问子组件的方法或属性:通过ref可以获取子组件的实例,并调用其方法或访问其属性。
import React, { useRef } from 'react';

function ChildComponent() {
  const childRef = useRef(null);

  const handleClick = () => {
    childRef.current.doSomething();
  }

  return (
    <div>
      <button onClick={handleClick}>Click</button>
      <Child ref={childRef} />
    </div>
  );
}

const Child = React.forwardRef((props, ref) => {
  const doSomething = () => {
    console.log('Doing something...');
  }

  // 将ref引用绑定到组件的实例
  React.useImperativeHandle(ref, () => ({
    doSomething
  }));

  return <div>Child Component</div>;
});
  1. 获取DOM元素:通过ref可以获取组件渲染后的DOM元素,并进行操作。
import React, { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  }

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
}
  1. 动态引用:通过ref可以在函数组件中动态地引用不同的组件或DOM元素。
import React, { useRef } from 'react';

function MyComponent() {
  const ref = useRef(null);
  const condition = true;

  const handleClick = () => {
    ref.current.doSomething();
  }

  return (
    <div>
      {condition ? (
        <ChildComponent ref={ref} />
      ) : (
        <OtherComponent ref={ref} />
      )}
      <button onClick={handleClick}>Click</button>
    </div>
  );
}

这些例子展示了一些使用React的ref的常见场景,但实际上,ref的用途非常灵活,可以根据具体需求进行扩展和应用。

@yanlele yanlele added web框架 web 框架相关知识 美团 公司标签 labels Jul 9, 2023
@yanlele yanlele added this to the milestone Jul 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
web框架 web 框架相关知识 美团 公司标签
Projects
None yet
Development

No branches or pull requests

1 participant