[英]ForwardRef error with typescript and react-native
I'm getting a ts error when using forwardRef 使用forwardRef时出现TS错误
// [ts] Property 'forwardRef' does not exist on type 'typeof React'.
const MyComponent = React.forwardRef((props: Props, ref: any) => ...
In React Native the parent component is throwing this error: 在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
Any idea on how to solve it? 关于如何解决的任何想法?
According to the 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
is an optional argument, try the following: ref
是可选参数,请尝试以下操作:
Inside a class create a ref object with a type parameter equal to your desired target (in my case div
but View
also works in react-native) 在类内部创建一个ref对象,其类型参数等于您想要的目标(在我的情况下为
div
但View
也可以在react-native中使用)
private divRef: React.RefObject<div> = React.createRef();
In the interface that represents the props for the forwarded component expose it as an optional property 在表示转发组件的道具的接口中,将其公开为可选属性
interface Props {
ref?: React.RefObject<div>;
}
Declare the forwarded component with the type React.ComponentType
用
React.ComponentType
类型声明转发的组件
const ComponentWithForwardedRef: React.ComponentType<Props> =
React.forwardRef((props: Props, ref?: React.Ref<div>) => (
<div ref={ref}>{props.message}</div>
));
When an instance of the component with the forwarded ref is created send the created ref object as a prop 创建带有转发的ref的组件的实例后,将创建的ref对象作为prop发送
<ComponentWithForwardedRef ref={this.divRef} />
All in one: 一体:
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"));
Link for posterity: https://codesandbox.io/s/6v152q394k 后代链接: https : //codesandbox.io/s/6v152q394k
Dependencies (reference purposes) 依赖关系(参考目的)
"@types/react": "^16.3.11",
"@types/react-native": "^0.55.19",
"react-native": "0.55.2",
"typescript": "^2.8.1"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.