npx create-react-app my-app-ts --template typescript
import React from 'react';
interface AppProps {
}
interface AppState {
fruit: string
}
export default class App extends React.Component<AppProps, AppState>{
public state: AppState = {
fruit: '芒果'
}
render() {
return <div>
<h2>App组件</h2>
</div>
}
}
import React from 'react';
interface MyFCProps {
name: string
}
const MyFC: React.FunctionComponent<MyFCProps> = ({ name }) => {
return <h4>{name}</h4>
}
export default MyFC;
import React from 'react';
// &是TypeScript的交叉类型。
type MyFCProps = { count: number } & typeof defaultProps;
const defaultProps = {
count: 0
};
const MyFC: React.FunctionComponent<MyFCProps> = ({ count }) => {
return (
<h4> 数量:{ count}</h4>
)
};
MyFC.defaultProps = defaultProps;
export default MyFC;
import React from 'react';
export default function MyUseState() {
// React.useState是泛型函数
const [count, setCount] = React.useState<number>(0);
return (
<div>
<h4>数量:{count}</h4>
<button onClick={() => { setCount(count + 1) }}>增加</button>
</div>
)
}