使用forwardRef
时出现 ts 错误'employees' => [
'driver' => 'eloquent',
'model' => App\Employee::class,
],
在React Native中,父组件抛出此错误:
// [ts] Property 'forwardRef' does not exist on type 'typeof React'.
const MyComponent = React.forwardRef((props: Props, ref: any) => ...
有关如何解决它的想法吗?
答案 0 :(得分:3)
根据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
也可以在本机模式下工作)
private divRef: React.RefObject<div> = React.createRef();
在表示所转发组件的道具的接口中,将其公开为可选属性
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>
));
创建具有转发的引用的组件的实例时,将创建的引用对象作为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"