React+Typescript使用接口泛型处理props

好 刚讲完组件 那么 这次 我们来看一下 数据传递的 props

还是上文的案例 例如 我们想将 title 传给Hello组件
之前我们可以直接这样
在这里插入图片描述
以一个标签属性的形式传过去

而我们在子组件中 这样去使用
在这里插入图片描述
但现在 我们从编辑器中都可以看出 这种写法已经不行了

然后 我们将 hello 组件改成这样

import * as React from "react";

interface IProps {
    
    
    title: string
}

export default class hello extends React.Component<IProps> {
    
    

    public constructor(props:any){
    
    
        super(props);
    }
    public render() {
    
    
        return (
            <div>{
    
     this.props.title }</div>
        )
    }
}

其中 最大的不同在于 我们定义了一个接口 IProps
规定里面要有一个 string字符串类型的字段 叫title
然后 挂到 react的Component上进行泛型
然后 这是 我们的父子组件就都不报错了
在这里插入图片描述
在这里插入图片描述
当然 我们可以传多个数据

这里 我们给子组件一个 age 数字 20
在这里插入图片描述
然后子组件规定一下类型
在这里插入图片描述
这里 我们用了Number 说他是个数字类型 那么 我们父组件尝试改成 字符串试试
在这里插入图片描述
很显然 这里就报错了 这也是Ts的一个意义 能够加强代码的规范和可读性

好 最后 父组件代码如下

import Hello from "./components/hello";

function App() {
    
    
  return (
    <div className="App">
        hello React Typescript
        <Hello title = "高阶组件" age = {
    
     20 } />
    </div>
  );
}

export default App;

子组件代码

import * as React from "react";

interface IProps {
    
    
    title: string,
    age: number
}

export default class hello extends React.Component<IProps,any> {
    
    

    public constructor(props:any){
    
    
        super(props);
    }
    public render() {
    
    
        return (
            <div>
                <div>{
    
     this.props.title }</div>
                <div>{
    
     this.props.age }</div>
            </div>
        )
    }
}

然后 我们运行项目
在这里插入图片描述
也是没有任何问题

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/132341771