打字稿和本机反应的 ForwardRef 错误
Posted
技术标签:
【中文标题】打字稿和本机反应的 ForwardRef 错误【英文标题】:ForwardRef error with typescript and react-native 【发布时间】:2018-10-20 04:17:44 【问题描述】:我在使用 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
你知道如何解决吗?
【问题讨论】:
【参考方案1】:根据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 对象(在我的例子中是 div
,但 View
也适用于 react-native)
private divRef: React.RefObject<div> = React.createRef();
在表示转发组件的 props 的接口中,将其公开为可选属性
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"
【讨论】:
在我的例子中是React.Ref<htmlDivElement>
。我也不知道你为什么在界面道具中列出 ref。至少对我来说这不是必需的,也没有意义,因为它不是 props: Props
的一部分以上是关于打字稿和本机反应的 ForwardRef 错误的主要内容,如果未能解决你的问题,请参考以下文章
React 本机流程、打字稿和 Visual Studio Code