React自定义组件渲染初体验

要实现的效果:

        自定义两个组件,并展示在页面上。如下图:

新建一个项目:

        不会创建项目的话可以参考使用脚手架新建一个React项目

创建成功后可以把项目文件夹中src目录以及public目录中的初始内容全部删除。

创建组件:

        在项目文件夹的src目录下新建components目录,其中包含两个自定义组件,目录如下:

 Hello组件内容:

index.jsx:

import React, { Component } from 'react'
import hello from './index.module.css'

export default class Hello extends Component {
	render() {
		return <h2 className={hello.title}>Hello,React!</h2>
	}
}

index.module.css:

.title{
	background-color: rgb(127, 98, 255);
}

Welcome组件内容:

index.jsx:

import React, { Component } from 'react'
import './index.css'

export default class Welcome extends Component {
	render() {
		return <h2 className="title">Welcome React!</h2>
	}
}

index.css:

.title{
	background-color: rgb(102, 251, 9);
}

创建外壳组件:

        在src目录下新建App.jsx,在其中导入我们创建的Hello和Welcome组件,并暴露出去。

App.jsx完整代码:

//创建“外壳”组件App
import React, { Component } from 'react'
import Hello from './components/Hello'
import Welcome from './components/Welcome'

//创建并暴露App组件
export default class App extends Component {
	render() {
		return (
			<div>
				<Hello />
				<Welcome />
			</div>
		)
	}
}

引入外壳组件并渲染:

        在src目录下新建index.js文件,在其中引入外壳组件,并渲染到index.html上。

index.js完整代码:

//引入react核心库
import React from 'react'
//引入App组件
import App from './App'

//渲染App到页面
import {
    createRoot
} from 'react-dom/client';
const container = document.getElementById('root');
const root = createRoot(container);
root.render( < App/> );

在public文件夹下新建index.html:

index.html完整代码:(index.html在public目录下)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="theme-color" content="#000000" />
  <meta name="description" content="Web site created using create-react-app" />
  <title>666</title>
</head>

<body>
  <div id="root"></div>
</body>

</html>

项目完整目录:

 运行:

在项目终端输入npm start。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值