Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用类对象作为属性与Typescript进行反应_Reactjs_Typescript - Fatal编程技术网

Reactjs 使用类对象作为属性与Typescript进行反应

Reactjs 使用类对象作为属性与Typescript进行反应,reactjs,typescript,Reactjs,Typescript,下面的示例输出了SomeClass的一个实例-这是可以预期的。问题:有没有一种方法可以省略DisplayModelComponentProps接口并直接传递要显示为prop的对象 class SomeClass { public someProperty:string = "some string"; public someFunction():string { return "another string"; } } interface DisplayModelComponentPr

下面的示例输出了SomeClass的一个实例-这是可以预期的。问题:有没有一种方法可以省略DisplayModelComponentProps接口并直接传递要显示为prop的对象

class SomeClass {
  public someProperty:string = "some string";
  public someFunction():string { return "another string"; }
}

interface DisplayModelComponentProps {
    obj:SomeClass
}

const DisplayModelComponent: React.FC<DisplayModelComponentProps> = props => {
  return(<p>{props.obj.someProperty}</p>
  )
}

export function Test(): JSX.Element {
 const someObj:SomeClass = new SomeClass();
 const props = { obj: someObj }

  return(<div><DisplayModelComponent {...props}></DisplayModelComponent></div>)
}

发生此错误的原因是,当扩展
SomeClass
的实例时,
someFunction
属性丢失。这就是为什么Typescript抱怨组件道具中缺少
someFunction

您可以检查有关排列运算符和属性复制方式的回答:


考虑到这一点,我认为只要您尝试将类用作接口时涉及到方法,您就无法做到这一点。

谢谢您的回答。我发现这可以完成任务,但它显然不是一个干净的解决方案:
return(“}}>)
Property 'someFunction' is missing in type '{ someProperty: string; }' but required in type 'SomeClass'.