React组件使用泛类型
首页 > >    作者:lininn   2022年7月22日 17:34 星期五   热度:779°   百度已收录  
时间:2022-7-22 17:34   热度:779° 

class类组件:

// 定义组件
class MyComponent<P> extends React.Component<P> {
  internalProp: P;
  constructor(props: P) {
    super(props);
    this.internalProp = props;
  }
  render() {
    return (
<span>hello world</span>
    );
  }
}

// 使用组件
type IProps = { name: string; age: number; };

<MyComponent<IProps> name="React" age={18} />;          // Success
<MyComponent<IProps> name="TypeScript" age="hello" />;  // Error
 函数组件:

interface IProps {
  name: string
}

const App = (props: IProps) => {
  const {name} = props;

  return (
<div className="App">
<h1>hello world</h1>
<h2>{name}</h2>
</div>
  );
}

export default App;
https://blog.51cto.com/u_14082075/5043255

二维码加载中...
本文作者:lininn      文章标题: React组件使用泛类型
本文地址:?post=560
版权声明:若无注明,本文皆为“覆手为雨”原创,转载请保留文章出处。
分享本文至:

返回顶部    首页    手机版本    后花园   会员注册   
版权所有:覆手为雨    站长: lininn