javascript - 打字稿和本机反应的 ForwardRef 错误
问题描述
使用 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
关于如何解决它的任何想法?
解决方案
根据定义:
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 对象作为道具发送
<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"
推荐阅读
- c - C使用函数而不调用其参数
- ruby-on-rails - 从 google auth 回来后,在 rails 5 中,控制器中的 flash 和 session 都是空的
- wix - WIX Bootstrapper - 卸载使用实例转换的 MSI
- bash - 用于远程执行 SSH 命令的 Bash 脚本函数包装器
- python - 在 anaconda 中调用 github 包时出现语法错误
- c# - 是否可以在 Win Forms 应用程序中使用 Entity Framework Core?/ 未找到参考文献警告
- reactjs - 对话框没有点击 onClick 事件
- java - 声明一个私有字符串数组和数组元素的初始化给出一个错误
- php - 如何在 ionic 4 中将图像上传到数据库 MYSQL?
- docker - Docker - 由于缺少 root 访问权限,父映像执行失败