一 组件的定义
/*
* @Description:
* @Version: 2.0
* @Autor: sun
* @Date: 2022-10-14 22:21:24
* @LastEditTime: 2022-10-14 22:33:55
*/
import React, { Component } from 'react';
export default class App extends Component {
constructor() {
super()
this.state = {
message: "你好啊 React"
}
}
render() {
const { message } = this.state
return (
<div>
<div>渲染App组件</div>
<h2>{ message }</h2>
</div>
)
}
}
/*
函数式组件的特点:
1 没有this对象
2 没有内部状态(hooks)
*/
export default function App() {
return (
<div>
<div>我是函数组件: App组件</div>
<h2>counter</h2>
<button>+1</button>
<h2>你好啊,测试内容</h2>
</div>
)
}
二 组件生命周期
/*
* @Description:
* @Version: 2.0
* @Autor: sun
* @Date: 2022-10-14 22:21:24
* @LastEditTime: 2022-10-15 00:16:13
*/
import React, { Component } from 'react'
class Cpn extends Component {
render () {
return (
<div>
Cpn组件
</div>
)
}
componentWillUnmount() {
//会在组件卸载及销毁之前直接调用
//在此方法中执行必要的清理操作
//清除timer 取消网络请求或者清除
console.log("组件被调用componentWillUnmount方法")
}
}
export default class App extends Component {
constructor() {
super();
//通过给this.state赋值对象来初始化内部的state
//为通过绑定实例(this)
console.log("执行了组件的constructor")
this.state = {
count: 0,
isShow: true,
}
}
render() {
console.log("执行了组件的render函数")
return (
<div>
我是App组件
<h2>当前计数: { this.state.count }</h2>
<button onClick={ e => this.inCrement() }>+1</button>
<br />
<button onClick={ e => this.changeCpn() }>切换</button>
{ this.state.isShow && <Cpn /> }
</div>
)
}
changeCpn() {
this.setState({
isShow: !this.state.isShow
})
}
inCrement() {
this.setState({
count: this.state.count + 1
})
}
componentDidMount() {
//会在组件挂载后(插入DOM树中)立即调用
//通常可以在这里可以操作:
//1 依赖dom操作可以在这里进行
//2 在此处发送网络请求就最好(官方建议)
// 可以在此处添加一些 订阅(会在componentWillUnmount取消订阅)
console.log("执行了组件的componentDidMount方法")
}
componentDidUpdate(prevProps, prevState, snapshot) {
//会在更新后被立即调用, 首次渲染不会被执行
// 当组件更新后可以在此处对DOM进行操作
// 如果你对更新前后props进行比较,也可以选择此处进行网络请求
console.log("执行了组件的componentDidUpdate方法")
}
}
三 组件间的嵌套
/*
* @Description:
* @Version: 2.0
* @Autor: sun
* @Date: 2022-10-14 22:21:24
* @LastEditTime: 2022-10-15 00:17:24
*/
import React, { Component } from 'react';
//header
function Header() {
return <h2>我是Header组件</h2>
}
//Main
function Banner() {
return <h3>我是Banner组件</h3>
}
function ProductList() {
return (
<div>
<ul>
<li>商品1</li>
<li>商品2</li>
<li>商品3</li>
<li>商品4</li>
</ul>
</div>
)
}
function Main(){
return (
<div>
<Banner />
<ProductList />
</div>
)
}
//Footer
function Footer(){
return <h2>我是Footer组件</h2>
}
class App extends Component {
render() {
return (
<div>
<Header />
<Main />
<Footer />
</div>
);
}
}
export default App;