专业编程基础技术教程

网站首页 > 基础教程 正文

React学习笔记:创建组件

ccvgpt 2024-11-21 11:13:26 基础教程 4 ℃


1.理解组件

Component和props

React学习笔记:创建组件

Component是React app的关键构建块,Stateless component(无状态组件)是将React内容渲染给用户的函数,props是组件之间传递渲染数据的方法。

无状态组件被定义为返回使用JSX和HTML定义的React元素的函数,props被定义为元素属性。

2.项目创建

①创建项目命令行

npx create-react-app projectName ;

②进入项目:

cd projectName;

③启动项目

run start

④安装依赖包:

npm install packageName

⑤安装及导入模块,以Bootstrap为例

cd projectName;
npm install bootstrap;

模块被自动安装到项目中的node_modules文件夹中。

导入bootstrap模块

使用import关键字将模块导入到src文件夹中的index.js文件中:

import 'bootstrap/dist/css/bootstrap.min.css';

导入的模块路径从模块一级路径开始

3.渲染HTML内容

(1)定义组件

React组件定义有三种方法:

1 定义组件函数,使用export default输出组件

function componentName(){
  return(组件内容元素)
}

export default componentName;

2 使用export defaulthe 定义并导出组件:

export default componentName(){
  return(组件内容元素)
  }
  

3 使用class和extends定义组件,使用export default输出组件,该方法需要在导入react模块时同时导入Component模块即:

  import React,{Component} from 'react';
  class componentName extends Component{
 render(){
  return(组件内容元素);
}
} 
 export default componentName;

组件函数中,使用关键字return返回渲染结果,换行需要加括号。

在上面的定义组件中,return(返回)中的内容是我们想要显示给用户的内容。这个过程叫做渲染。

(2)JSX文件中的HTML代码会被调用的createElement方法转换成向用户显示内容的对象。

React.createElement方法将html代码转换成React元素:

React.createElement('htmlTag',className:className,'html内容');

例如:

React.createElement("h1", 
{ className: "bg-primary text-white text-center p-2" },
  "Hello Adam");

当组件渲染字符串值时,组件将作为文本内容包含在父元素中。

(3)我们可以使用箭头函数省略关键字return 导出(export)定义的组件函数,导出默认组件App时可以省略组件名。

可以使用export以变量的形式声明一个箭头函数组件,然后用export default导出组件:

export const ComponentName=()=>
<htmlTag>Content</htmlTag>
export default ComponentName;

3.渲染其他组件

不同的组件可以拥有不同的内容和功能,可以不同的组件组合起来,创建一个负责的Web应用程序。子组件要和父组件放在同一个文件夹中。

1 定义子组件

在定义子组件时,我们要用export加子组件直接导出:

export childComponentName(){
return(子组件内容)
}

2 导入子组件

在父组件文件中使用import导入子组件:

import { childComponentName } from './ childComponentName.js';

子组件名称与子组件文件名可以不一致。因为在组合不同功能的组件时,使用的是组件文件中的组件。但为了方便,我们尽量让组件名和组件文件名一致。

3 组合组件

将子组件作为父组件的一个元素标签进行组合:

export default function App(){
  return(
    <div>
      <h1>附组件内容/h1>
      < childComponentName />//子组件  
    </div>
  )
}

Tags:

最近发表
标签列表