标签: react-forwardref

类型错误:组件不是添加forwardRef的函数

您好,我试图将forwardRef添加到子组件,但在添加forwardRef时得到以下信息: TypeError: Component is not a function

该组件定义如下:

import React from 'react';
import { forwardRef } from 'react';
import { TextInputFocusEventData } from 'react-native';
import { NativeSyntheticEvent, StyleSheet } from 'react-native';
import { Input, InputProps } from 'react-native-elements';
import { Metrics, Colors } from '../../theme';
import Icons from '../Icons';


const CustomTextInput2 = forwardRef<TextInput, ICustomtextnputProps>((props, ref) => {
    const { name, required } = props;

    return (
        <Input
            rightIcon={<Icons name="right" />}
            placeholder={name?.concat(required ? '*' : '')}
            inputContainerStyle={styles.inputContainer}
            inputStyle={styles.inputText}
            {...props}
        />
    ) …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-native react-hooks react-forwardref

29
推荐指数
1
解决办法
1万
查看次数

将 forwardRef 与 proptypes 和 eslint 一起使用

我正在尝试使用eslintprop-types在项目中将 forwardRef 用于 Button 。

这是我到目前为止所尝试的,以及我每次得到的错误:

第一次尝试

function Button ({ action = { callback: () => {}, title: 'unknown' } }, ref) {
  return (<button ref={ref} onClick={action.callback} title={action.description} type="button">{action.icon || action.title}</button>)
}

Button.propTypes = {
  action: Action.isRequired
}

export default forwardRef(Button)
Run Code Online (Sandbox Code Playgroud)

这将在控制台中给我以下警告: Warning: forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?

第二次尝试

function ButtonFunction ({ action = { callback: () => {}, title: 'unknown' } }, ref) { …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs eslint react-proptypes react-forwardref

27
推荐指数
2
解决办法
1万
查看次数

如何检查React功能组件中的div是否溢出

我试图找出 div 是否有溢出文本,show more如果有则显示链接。我找到了这个 stackoverflow 答案来检查 div 是否溢出。根据这个答案,我需要实现一个函数,它可以访问相关元素的样式,并进行一些检查以查看它是否溢出。如何访问元素的样式。我尝试了2种方法

1. 使用参考

import React from "react";
import "./styles.css";

export default function App(props) {
  const [showMore, setShowMore] = React.useState(false);
  const onClick = () => {
    setShowMore(!showMore);
  };

  const checkOverflow = () => {
    const el = ref.current;
    const curOverflow = el.style.overflow;

    if ( !curOverflow || curOverflow === "visible" )
        el.style.overflow = "hidden";

    const isOverflowing = el.clientWidth < el.scrollWidth 
        || el.clientHeight < el.scrollHeight;

    el.style.overflow = curOverflow;

    return isOverflowing;
  };

  const …
Run Code Online (Sandbox Code Playgroud)

javascript css reactjs react-forwardref

13
推荐指数
2
解决办法
2万
查看次数

如何在组件中使用 React.forwardRef() 和自己的 ref ?


我正在尝试使用React.forwardRef()并同时React.useRef()在组件中使用的任务。

问题我只能
使用使用forwardRef 属性。所以,我不知道如何一起使用它们。示例代码:myOwnRef ref

interface IExampleInputProps {
    value: string,
    onChange: (event: ChangeEvent<HTMLInputElement>) => void
}
const ExampleInput = forwardRef<HTMLInputElement | null, IExampleInputProps>(({value, onChange}, ref) => { // can't to use "ref" parameter
    const myOwnRef = React.useRef<HTMLInputElement | null>(null);

    return <input ref={el => {
        myOwnRef.current = el; // => OK
        if (ref) { // trying to use the ref passed from the forwardRef function
            ref.current = el; // => ERROR
        } …
Run Code Online (Sandbox Code Playgroud)

reactjs react-forwardref use-ref

12
推荐指数
1
解决办法
5371
查看次数

理解:警告:不能给函数组件提供引用

我知道 refs 用于直接访问 DOM 元素而不改变状态。我读到无法为功能组件提供引用,因为它们没有状态。

Refs 不能附加到函数组件。虽然,我们可以定义 refs 并将它们附加到 DOM 元素或类组件。底线是——函数组件没有实例,所以你不能引用它们。

取自:https : //blog.logrocket.com/cleaning-up-the-dom-with-forwardref-in-react/

我还是不明白。

我正在使用TooltipAnt Design ( https://ant.design/components/tooltip/ ) 中的Button组件、组件和自定义CircleButton组件。

鉴于以下 JSX:

<Tooltip placement="left" title={"Lock slot"}>
  <CircleButton onClick={() => execute(client.close)} icon={<LockOutlined />} disabled={loading} />
</Tooltip>
Run Code Online (Sandbox Code Playgroud)

还有我的 CircleButton 组件。像这样使用,它会产生警告

const CircleButton = (props) => // gives the warning
  <Button shape="circle" size="small" style={{ marginRight: "8px" }} {...props} />
Run Code Online (Sandbox Code Playgroud)

警告:不能为函数组件提供引用。尝试访问此引用将失败。你的意思是使用 React.forwardRef() 吗?

请注意,尽管有警告,但一切都按预期工作。

如果我按如下方式编辑它,它会正常工作,为什么?

const CircleButton = forwardRef((props, ref) => // doesn't give …
Run Code Online (Sandbox Code Playgroud)

javascript ref reactjs react-forwardref

11
推荐指数
2
解决办法
7700
查看次数

ReactforwardRef - 访问组件内和父级中的引用

我需要访问组件内文本区域的引用。在组件内,它很简单:

const MyComponent = () => {
  const inputRef = useRef();

  return <textarea ref={inputRef} />
}
Run Code Online (Sandbox Code Playgroud)

现在 ref 在 MyComponent 中可用,我可以将它用于一些内部逻辑。

在某些情况下,我也需要从父组件访问引用。在这种情况下,我可以使用forwardRef:

const MyComponent = React.forwardRef((props, ref) => {
  return <textarea ref={ref} />
})

// In some parent
const MyParent = () => {
  const inputRefFromParent = useRef();
  return <MyComponent ref={inputRefFromParent} />
}
Run Code Online (Sandbox Code Playgroud)

现在我可以从父组件访问 ref textarea,并将其用于父组件中的逻辑。

我发现自己处于这样的情况:我需要使用 中的 ref 进行一些内部逻辑MyComponent,但我可能还需要从 中获取该引用MyParent。我怎样才能做到这一点?

javascript reactjs react-forwardref

11
推荐指数
2
解决办法
8977
查看次数

React 中 ForwardRefExoticComponent 和 ForwardRefRenderFunction 有什么区别?

我正在编写一个 React 组件,它可以将 ref 转发给它的孩子

我发现对于函数组件的返回类型,我可以使用ForwardRefExoticComponentForwardRefRenderFunction。但我不确定它们之间有什么区别。

到目前为止,当使用ForwardRefExoticComponent 时,我可以扩展它而ForwardRefRenderFunction不能?我在这里发布了一个与我的案例相关的问题:How to export forwardRef with ForwardRefRenderFunction

如果有人知道他们之间的区别以及他们所做的事情,请帮助我。因为 React 团队似乎没有关于它们的文档(但它们在 react 包中)

javascript typescript reactjs react-forwardref

10
推荐指数
1
解决办法
4664
查看次数

返回 input 或 textArea 的元素的 React/Typescript forwardRef 类型

我正在尝试使用 react 和 typescript 为我们的应用程序创建一个通用的文本输入组件。我希望它能够成为基于给定道具的输入元素或 textarea 元素。所以它看起来有点像这样:

import {TextArea, Input} from 'ourComponentLibrary'

export const Component = forwardRef((props, ref) => {
  const Element = props.type === 'textArea' ? TextArea : Input

  return (
    <Element ref={ref} />
  )
})
Run Code Online (Sandbox Code Playgroud)

这段代码工作正常。然而,当试图合并类型时,它变得有点冒险。ref 类型应该是HTMLInputElementHTMLTextAreaElement基于传递的typeprop。在我的脑海中,它看起来像这样:

interface Props {
  ...
}

export const Component = forwardRef<
  HTMLInputElement | HTMLTextAreaElement,
  Props
>((props, ref) => {
  ...
});
Run Code Online (Sandbox Code Playgroud)

但是我知道这不完全是我需要的。因此,错误: Type 'HTMLInputElement' is missing the following properties from type 'HTMLTextAreaElement': cols, rows, textLength, wrap …

typescript reactjs react-ref react-forwardref

9
推荐指数
2
解决办法
3406
查看次数

如果我们可以简单地在 props 中传递创建的 ref ,为什么我们需要 ReactforwardRef 呢?

根据 React 文档,将 ref 传递给子组件的正确方法如下:

import React from 'react';

const Input = React.forwardRef((props, ref) => {
  React.useEffect(() => {
    ref.current.focus();
  }, []);
  return <input type="text" ref={ref} />;
});

export default function App() {
  const inputRef = React.createRef();
  return (
    <div>
      <Input ref={inputRef} />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试将创建的 ref 作为普通 prop 以任何其他名称(然后是“ref”)传递,这也会按预期工作。

import React from 'react';

const Input = (props) => {
  React.useEffect(() => {
    props.inputRef.current.focus();
  }, []);
  return <input type="text" ref={props.inputRef} />;
};

export default function App() {
  const inputRef …
Run Code Online (Sandbox Code Playgroud)

reactjs react-ref react-forwardref

9
推荐指数
1
解决办法
6619
查看次数

模拟forwardRef组件玩笑mockImplementation与打字稿

当组件包装在forwardRef 中时,您打算如何处理测试文件中的模拟组件?mockImplementation 不在方法上,而是在属性渲染上。

import React from 'react';
import Component from './Component';
import mocked from 'ts-jest/utils'

jest.mock('./Component');

const mockComponent(Component);

mockComponent.mockImplementation(() => <></>) /* this returns type error that mockImplementation is not a function */

mockComponent.render.mockImplementation(() => <></>) /* this works but get a typescript error */

Run Code Online (Sandbox Code Playgroud)

我看到的打字稿错误是

TS2339: Property 'render' does not exist on type 'MockedFunction   "li", {}>, "button" | "slot" | "style" | "title" | "className" | "classes" | "innerRef" | "selected" | "dense" | "key" | "value" | "defaultChecked" …
Run Code Online (Sandbox Code Playgroud)

unit-testing typescript reactjs jestjs react-forwardref

8
推荐指数
1
解决办法
4626
查看次数