React的React.FC与React.Component的用法

发布时间:2021-09-05 16:50:56 作者:chen
来源:亿速云 阅读:511

本篇内容主要讲解“React的React.FC与React.Component的用法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“React的React.FC与React.Component的用法”吧!

目录

React 的组件可以定义为 函数(React.FC<>)或class(继承 React.Component) 的形式。

一、React.FC<>

1.React.FC是函数式组件,是在TypeScript使用的一个泛型,FC就是FunctionComponent的缩写,事实上React.FC可以写成React.FunctionComponent:

const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
  <div>{message}</div>
);

2.React.FC 包含了 PropsWithChildren 的泛型,不用显式的声明 props.children 的类型。React.FC<> 对于返回类型是显式的,而普通函数版本是隐式的(否则需要附加注释)。

3.React.FC提供了类型检查和自动完成的静态属性:displayName,propTypes和defaultProps(注意:defaultProps与React.FC结合使用会存在一些问题)。

4.我们使用React.FC来写 React 组件的时候,是不能用setState的,取而代之的是useState()、useEffect等 Hook API。

例子(这里使用阿里的Ant Desgin Pro框架来演示):

const SampleModel: React.FC<{}> = () =>{   //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 React.Component

如需定义 class 组件,需要继承 React.Component。React.Component是类组件,在TypeScript中,React.Component是通用类型(aka React.Component<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:简单来说,不知道用什么组件类型时,就用 React.FC。

到此,相信大家对“React的React.FC与React.Component的用法”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. InvalidateRect()与Invalidate()的用法
  2. javascript中for in与in的用法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

react

上一篇:JavaScript中三个点号是什么意思

下一篇:Gitlab的CI/CD功能怎么用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》