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。

猜你喜欢

转载自blog.csdn.net/m0_59778008/article/details/127212779