React组件使用泛类型

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
相关文章