Case I, I can accept those code as the picture shows, we define the ref in parent component and pass it to child component

App.js

import { useRef } from 'react';
import MyInput from './MyInput.js';

export default function Form() {
  const ref = useRef(null);

  function handleClick() {
    ref.current.focus();
  }

  return (
    <form>
      <MyInput label="Enter your name:" ref={ref} />
      <button type="button" onClick={handleClick}>
        Edit
      </button>
    </form>
  );
}

MyInput.js

import { forwardRef } from 'react';

const MyInput = forwardRef(function MyInput(props, ref) {
  const { label, ...otherProps } = props;
  return (
    <label>
      {label}
      <input {...otherProps} ref={ref} />
    </label>
  );
});

export default MyInput;

Case II,the component Input was defined as following ,

import * as React from 'react'

import { cn } from '@/lib/utils'

export interface InputProps
  extends React.InputHTMLAttributes<HTMLInputElement> {}

const Input = React.forwardRef<HTMLInputElement, InputProps>(
  ({ className, type, ...props }, ref) => {
    return (
      <input
        type={type}
        className={cn(
          'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
          className
        )}
        ref={ref}
        {...props}
      />
    )
  }
)
Input.displayName = 'Input'

export { Input }

这是在另一个文件chat.js中使用的,剧集ID如下

import { Input } from './ui/input'

<Input
        value={previewTokenInput}
        placeholder="OpenAI API key"
        onChange={e => setPreviewTokenInput(e.target.value)}
/>

有些事情把我搞糊涂了,父级没有定义Ref变量,直接使用.这是使用ForwardRef的新方法吗?

代码是从https://github.com/vercel-labs/ai-chatbot开始,

  • /Component/chat.tsx
  • /Component/ui/input.tsx

推荐答案

有些事情把我搞糊涂了,父级没有定义引用变量,并且使用 直接go 吧.

仅仅因为子组件转发了react 引用并不意味着父组件一定需要传递一个.Reaction组件通常忽略它们不关心的props ,对于那些没有传递的props ,它们的值将只是未定义或接收默认/回退值(如果子组件是这样实现的).

这是使用ForwardRef的新方法吗?

不,这一直是React.forwardRef函数的工作方式.

这两个部分在" case "方面没有区别.

import { forwardRef } from 'react';

const MyInput = forwardRef(function MyInput(props, ref) { // ref forwarded
  const { label, ...otherProps } = props;
  return (
    <label>
      {label}
      <input
        {...otherProps}
        ref={ref} // passing ref through to HTML element
      />
    </label>
  );
});

export default MyInput;
const Input = React.forwardRef<HTMLInputElement, InputProps>( // ref forwarded
  ({ className, type, ...props }, ref) => {
    return (
      <input
        type={type}
        className={cn(
          '....',
          className
        )}
        ref={ref} // passing ref through to HTML element
        {...props}
      />
    )
  }
)

在转发react 裁判方面,这两个" case "是相同的.

两者101的不同之处在于,在第一个示例中,代码实际上是创建一个ref并将其传递给MyInput组件.

import { useRef } from 'react';
import MyInput from './MyInput.js';

export default function Form() {
  const ref = useRef(null); // <-- created ref

  function handleClick() {
    ref.current.focus();
  }

  return (
    <form>
      <MyInput label="Enter your name:" ref={ref} /> // <-- passed ref
      <button type="button" onClick={handleClick}>
        Edit
      </button>
    </form>
  );
}

同样的100也适用于第二个代码示例:

import { useRef } from 'react';
import { Input } from './ui/input';

export default function Form() {
  const ref = useRef(null);

  function handleClick() {
    ref.current.focus();
  }

  return (
    <form>
      <Input
        value={previewTokenInput}
        placeholder="OpenAI API key"
        onChange={e => setPreviewTokenInput(e.target.value)}
        ref={ref}
      />
      <button type="button" onClick={handleClick}>
        ....
      </button>
    </form>
  );
}

Reactjs相关问答推荐

在带有和设计的表格中禁用和取消选中复选框

如何使用皮金贴图在Reactjs中制作 map 上的点之间的线的动画?

一键MUI导出

用于获取带有事件处理程序的API的动态路由

REACTION-Easy-SORT返回.map错误

如何在MUI x图表条形图上放置圆角?

Gitlab CI和VITE环境变量出现问题

如何在中间件中获取 nextAuth 会话

对于 ref 上的可见 prop 或 open 方法来react 组件,哪种方式更好?

在react的useEffect钩子中,我的函数被调用,但只有第一个函数能够改变状态,第二个函数无法改变状态.

如何在next.js 13中仅在主页导航栏上隐藏组件?

BrowserRouter改变了URL但没有链接到页面

字段是必需的,当它没有定义时

为嵌套路由配置一个不存在的 url 的重定向

使用 axios 响应路由 Dom 操作

将路径数组传递给Route会引发错误

如何从一组对象映射 MUI 5 图标并更改其 colored颜色 ?

React - useParams() 不会失败 null / undefined 判断

服务器端分页未按预期工作

将 C# Razor 条件块转换为 React.js 代码