我在本文中描述了HOC:https://medium.com/@jrwebdev/react-higher-order-component-patterns-in-typescript-42278f7590fb
我的代码(HOC):
import * as React from 'react';
import Dropzone from 'react-dropzone'
export const addImage = <P extends object>(WrappedComponent: React.ComponentType<P>) => {
return class extends React.Component {
render() {
return <Dropzone noClick onDrop={()=>{console.log('drop')}}>
{({ getRootProps, getInputProps }) => (
<div {...getRootProps()} onClick={()=>{console.log('aa')}}>
<input {...getInputProps()} />
<WrappedComponent {...this.props} />;
</div>
)}
</Dropzone>
}
};
}
在其他组件中:
addImage(<Img src={item} />)
在HOC错误中:'{子代?:ReactNode; }”可分配给类型“ P”的约束,但可以使用约束“对象”的另一子类型实例化“ P”
如何解决该错误?
答案 0 :(得分:3)
我认为您需要指定从addImage
返回的类的道具类型:
export const addImage = <P extends object>(WrappedComponent: React.ComponentType<P>) => {
return class extends React.Component<P> { // <- The "<P>" is the missing part
这应该摆脱屏幕快照中的警告。但是此后,亚历杭德罗·加西亚·安格拉达(Alejandro Garcia Anglada)关于如何正确使用HOC的所有评论都是正确的。
答案 1 :(得分:1)
在您的情况下,您将需要以这种方式包装您的组件。
<ul class="navbar-nav leftside mr-auto">
@foreach($categories as $category)
<li class="nav-item active">
@if($category->id == 2 )
<a class="nav-link" href="{{ route('index', ['id' => $category->id])}}">{{$category->name}} <span class="sr-only">(current)</span></a>
@endif</li>
</li>
@endforeach
</ul>
const Image = ({ item }) => <Img src={item} />
,而该参数就是您传递给P
的道具的类型Image
答案 2 :(得分:0)
尝试将P
声明为接口
import * as React from 'react';
import Dropzone from 'react-dropzone'
interface P extends Object {
...
}
export const addImage = (WrappedComponent: React.ComponentType<P>) => {
return class extends React.Component {
render() {
return <Dropzone noClick onDrop={()=>{console.log('drop')}}>
{({ getRootProps, getInputProps }) => (
<div {...getRootProps()} onClick={()=>{console.log('aa')}}>
<input {...getInputProps()} />
<WrappedComponent {...this.props} />;
</div>
)}
</Dropzone>
}
};
}
答案 3 :(得分:0)
export const addImage = <P extends object>(WrappedComponent: React.ComponentType<P &
Props>, props: Props, ref) => {
return class extends React.Component<P & Props, State> {
render() {
<input/>
...
如何在输入中添加引用?