Reactjs 打字脚本+;React:将类作为外部函数arg传递

Reactjs 打字脚本+;React:将类作为外部函数arg传递,reactjs,typescript,Reactjs,Typescript,我有一些函数,我想在兼容的不同React类中作为方法重用。在Typescript中是否可以将类传递给函数并正确键入 我想做这样的事 // function to be reused across classes const func = (class: [class type]) => this.setState({ key: "value" }) // class 1 that calls the function in a method class Foo extends React

我有一些函数,我想在兼容的不同React类中作为方法重用。在Typescript中是否可以将类传递给函数并正确键入

我想做这样的事

// function to be reused across classes
const func = (class: [class type]) => this.setState({ key: "value" })

// class 1 that calls the function in a method
class Foo extends React.Component<{}, {}> {
  callFunc = () => {
    func(this)
  }
  ...
}

// class 2 that calls the function in a method
class Bar extends React.Component<{}, {}> {
  callFunc = () => {
    func(this)
  }
  ...
}
//跨类重用的函数
const func=(class:[类类型])=>this.setState({key:“value”})
//在方法中调用函数的类1
类Foo扩展了React.Component{
callFunc=()=>{
func(本)
}
...
}
//在方法中调用函数的类2
类栏扩展了React.Component{
callFunc=()=>{
func(本)
}
...
}
我在JS中使用了它,但是转到typescript,我无法在类的
func
args中获得正确的类型。我可以看到,它必须是某种联合类型,以允许特定的类,但IDK如何实现它。有什么想法吗


是否有更好的方法来执行此操作?

函数参数需要指定需要由客户端类实现的约定。在这种情况下,参数应该是一个
React.Component
,该组件的某些字段处于状态,也可能有函数将使用的一些方法。为了获得额外的方法,我们可以使用交叉点类型(
A&B
)来指定参数是带有一些额外方法的
React.Component

// function to be reused across classes
const func = (cls: React.Component<any, { key: string, optionalKey?: string }> & { requiredMethod(): void; optionalMethod?(): void}) => {
  cls.setState({ key: "value" })
  cls.requiredMethod();
  if(cls.optionalMethod)cls.optionalMethod();
}

// class 1 that calls the function in a method
class Foo extends React.Component<{}, { key: string }> {
  callFunc = () => {
    func(this)
  }
  requiredMethod(){}
}

// class 2 that calls the function in a method
class Bar extends React.Component<{}, {key: string, optionalKey: string }> {
  callFunc = () => {
    func(this)
  }

  requiredMethod(){}
  optionalMethod(){}
}
//跨类重用的函数
const func=(cls:React.Component&{requiredMethod():void;optionalMethod?():void})=>{
cls.setState({key:“value”})
cls.requiredMethod();
if(cls.optionalMethod)cls.optionalMethod();
}
//在方法中调用函数的类1
类Foo扩展了React.Component{
callFunc=()=>{
func(本)
}
requiredMethod(){}
}
//在方法中调用函数的类2
类栏扩展了React.Component{
callFunc=()=>{
func(本)
}
requiredMethod(){}
optionalMethod(){}
}

为什么不干脆
constfunc=(cls:React.Component)=>cls.setState({key:“value”})
?是否要求类中存在状态的特定字段?然后只需在state泛型参数上指定它们:
constfunc=(cls:React.Component)=>cls.setState({key:“value”})
@TitianCernicova Dragomir您的方法让我半途而废。如果我想访问类上除了内置的
setState
之外的其他用户定义的方法或属性怎么办?您需要将它们添加到参数类型中,
const func=(cls:React.Component&{method():void})=>cls.method