gpt4 book ai didi

javascript - typescript 和 react-native 的 ForwardRef 错误

转载 作者:数据小太阳 更新时间:2023-10-29 06:14:17 25 4
gpt4 key购买 nike

使用 forwardRef 时出现ts 错误

// [ts] Property 'forwardRef' does not exist on type 'typeof React'.
const MyComponent = React.forwardRef((props: Props, ref: any) => ...

在 React Native 中,父组件抛出此错误:

Invariant Violation: Element type is invalid: expected a string (for build-in components) or a class/function (for composite components) but got: object

有什么解决办法吗?

最佳答案

根据definitions :

function forwardRef<T, P = {}>(Component: RefForwardingComponent<T, P>): ComponentType<P & ClassAttributes<T>>;
interface RefForwardingComponent<T, P = {}> {
(props: P & { children?: ReactNode }, ref?: Ref<T>): ReactElement<any> | null;
propTypes?: ValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}

ref 是可选参数,尝试以下操作:

在一个类中创建一个 ref 对象,其类型参数等于您想要的目标(在我的例子中是 divView 也适用于 react-native)

private divRef: React.RefObject<div> = React.createRef();

在表示转发组件的 Prop 的界面中,将其作为可选属性公开

interface Props {
ref?: React.RefObject<div>;
}

声明转发的组件类型为React.ComponentType

const ComponentWithForwardedRef: React.ComponentType<Props> = 
React.forwardRef((props: Props, ref?: React.Ref<div>) => (
<div ref={ref}>{props.message}</div>
));

创建具有转发 ref 的组件实例时,将创建的 ref 对象作为 prop 发送

<ComponentWithForwardedRef ref={this.divRef} />

一应俱全:

import * as React from "react";
import { render } from "react-dom";

interface Props {
message: string;
ref?: React.RefObject<div>;
}

const ComponentWithForwardedRef: React.ComponentType<Props> =
React.forwardRef((props: Props, ref?: React.Ref<div>) => (
<div ref={ref}>{props.message}</div>
));

class App extends React.Component<Props> {
private divRef: React.RefObject<div> = React.createRef();

public componentDidMount() {
const div = this.divRef.current;
// check the console!
console.log(div);
}

public render() {
return (
<ComponentWithForwardedRef ref={this.divRef} {...this.props} />
)
}
}

render(<App message="hello world" />, document.getElementById("root"));

后代链接:https://codesandbox.io/s/6v152q394k

依赖关系(引用目的)

"@types/react": "^16.3.11",
"@types/react-native": "^0.55.19",
"react-native": "0.55.2",
"typescript": "^2.8.1"

关于javascript - typescript 和 react-native 的 ForwardRef 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50263658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com