【问题标题】:How can I pass props and state interface to a React class if I extend a custom class?如果我扩展自定义类,如何将道具和状态接口传递给 React 类?
【发布时间】:2020-11-13 06:55:02
【问题描述】:

这就是在 typescript 中实现 react 类的方式:

export class Signup extends Component<SignupProps, SignupState> {}

interface SignupProps {
  onSignup: (e: FormEvent, state: SignupState) => void;
}
interface SignupState {
  data: {
    email: string;
    password: string;
    name: string;
  };
}

由于我有注册和登录表单,为了防止代码重复,我创建了一个 BaseForm 类,我将所有可重用的逻辑放在其中并从那里继承。

   export class Signupextends BaseForm {}

但是我遇到了道具问题,我不知道如何传递道具和状态接口。

export class Signup<SignupProps, SignupState> extends BaseForm {}

在这种情况下,我收到了onSignup props 警告,但我在扩展 React.Component 时没有收到此警告

“属性 'onSignup' 不存在于类型 'Readonly & Readonly

  export class Signup extends BaseForm<SignupProps, SignupState> {}

在这种情况下,它说:“类型 'BaseForm' 不是通用的。”

我尝试了这两种方法,但都没有奏效。我看不出第三个选项是什么。

【问题讨论】:

  • 能否也包括props和state的定义?

标签: reactjs typescript interface


【解决方案1】:

我假设,您正在尝试将 Props 和 State 类型传递给未从 React 组件扩展的类。

尝试下一个代码,这应该适合你


class BaseForm<P,S> extends React.Component<P,S> {}

class SIgnup extends BaseForm<Props, State> {}

但是,我建议使用函数组合、高阶组件、高阶函数或渲染道具模式来使您的逻辑可重用。

在这里你可以找到more patterns

请看这里:


type Props = {
  // make proper types for args, don't use any
  children:(...args: any[])=>React.ReactNode
}

class BaseForm extends Component<Props,State> {  
   handleFoo=()=>{}
   handleBar=()=>{}
   
   render(){
     this.props.children({handleFoo: this.handleFoo, handleBar: this.handleBar})
   }
}

class Signup extends from React.Component {
  render(){
   <BaseForm>{
     ({handleFoo, handleBar})=><div>42</div>
   }</BaseForm>
  }
}

【讨论】:

    【解决方案2】:
    export class Signup extends BaseForm {}
    

    这是 BaseForm:

    export abstract class BaseForm extends React.Component<
      SignupProps,
      SignupState
    > {}
    

    这行得通。在我做研究的时候,我终于明白了为什么抽象类很方便。继承是使用抽象类的一个很好的例子。因为这个 BaseForm 类不会被实例化,并且由于 LoginForm 和 SignUpForm 将有 doSubmit() 方法和模式属性,所以我在 Base 类中设置了一个默认值:

    abstract schema: {} = {};
      //   defining doSubmit:(e:FormEvent):void was not accepted ???
    abstract doSubmit(e: FormEvent): void;
    

    然后在 SignUpForm 中实现它们如下:

    schema = {
        name: Joi.string().alphanum().min(5).required().label("Name"),
        password: Joi.string().min(5).max(15).required().label("Password"),
        email: Joi.string().email(),
      };
      doSubmit(e: FormEvent) {
        this.props.onSignup(e, this.state);
      }
    

    因为我将在 LoginForm 和 SignUpForm 中使用这个基类,这就是我定义接口的方式:

    interface SignupProps {
      onSignup?: (e: FormEvent, state: SignupState) => void;
      onLogin?: (e: FormEvent, state: SignupState) => void;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 2021-03-07
      • 2019-08-19
      • 2021-06-15
      • 1970-01-01
      • 2021-02-18
      相关资源
      最近更新 更多