您好,我试图将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
我正在尝试使用eslint和prop-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) 我试图找出 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)
我正在尝试使用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) 我知道 refs 用于直接访问 DOM 元素而不改变状态。我读到无法为功能组件提供引用,因为它们没有状态。
Refs 不能附加到函数组件。虽然,我们可以定义 refs 并将它们附加到 DOM 元素或类组件。底线是——函数组件没有实例,所以你不能引用它们。
取自:https : //blog.logrocket.com/cleaning-up-the-dom-with-forwardref-in-react/
我还是不明白。
我正在使用Tooltip
Ant 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) 我需要访问组件内文本区域的引用。在组件内,它很简单:
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
。我怎样才能做到这一点?
我正在编写一个 React 组件,它可以将 ref 转发给它的孩子
我发现对于函数组件的返回类型,我可以使用ForwardRefExoticComponent和ForwardRefRenderFunction。但我不确定它们之间有什么区别。
到目前为止,当使用ForwardRefExoticComponent 时,我可以扩展它而ForwardRefRenderFunction不能?我在这里发布了一个与我的案例相关的问题:How to export forwardRef with ForwardRefRenderFunction
如果有人知道他们之间的区别以及他们所做的事情,请帮助我。因为 React 团队似乎没有关于它们的文档(但它们在 react 包中)
我正在尝试使用 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 类型应该是HTMLInputElement
或HTMLTextAreaElement
基于传递的type
prop。在我的脑海中,它看起来像这样:
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 …
根据 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) 当组件包装在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) react-forwardref ×10
reactjs ×10
javascript ×6
typescript ×3
react-ref ×2
css ×1
eslint ×1
jestjs ×1
react-hooks ×1
react-native ×1
ref ×1
unit-testing ×1
use-ref ×1