React组件使用泛类型

Others 2022-07-22 09:34:05 2022-07-22 09:34:05 963 次浏览

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