React 的组件可以定义为 函数(
<>
)或class(继承) 的形式。
一、<>
1.是函数式组件,是在TypeScript使用的一个泛型,FC就是FunctionComponent的缩写,事实上
可以写成
:
const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
<div>{message}</div>
);
2. 包含了
PropsWithChildren
的泛型,不用显式的声明 的类型。
<>
对于返回类型是显式的,而普通函数版本是隐式的(否则需要附加注释)。
3.提供了类型检查和自动完成的静态属性:
displayName
,propTypes
和defaultProps
(注意:defaultProps
与结合使用会存在一些问题)。
4.我们使用来写 React 组件的时候,是不能用setState的,取而代之的是
useState()
、useEffect
等 Hook API。
例子(这里使用阿里的Ant Desgin Pro框架来演示):
const SampleModel: React.FC<{}> = () =>{ //<>为typescript使用的泛型
const [createModalVisible, handleModalVisible] = useState<boolean>(false);
return{
{/** 触发模态框**/}
<Button style={{fontSize:'25px'}} onClick={()=>handleModalVisible(true)} >样例</Button>
{/** 模态框组件**/}
<Model onCancel={() => handleModalVisible(false)} ModalVisible={createModalVisible} />
}
二、class xx extends
如需定义 class 组件,需要继承 。
是类组件,在TypeScript中,
是通用类型(aka
<PropType, StateType>
),因此要为其提供(可选)prop和state类型参数:
例子(这里使用阿里的Ant Desgin Pro框架来演示)::
class SampleModel extends React.Component {
state = {
createModalVisible:false,
};
handleModalVisible =(cVisible:boolean)=>{
this.setState({createModalVisible:cVisible});
};
return {
{/** 触发模态框**/}
<Button onClick={()=>this.handleModalVisible(true)} >样例</Button>
{/** 模态框组件**/}
<Model onCancel={() => handleModalVisible(false)} ModalVisible={this.state.createModalVisible} />
}
ps:简单来说,不知道用什么组件类型时,就用 。