生命周期
React的组件化
- 根据组件的定义方式,可以分为:函数组件和类组件
类组件的名称是大写字符开头(无论类组件还是函数组件),类组件需要继承自React.Component,类组件必须实现render函数 - 根据组件内部是否有状态需要维护,可以分为无状态组件和有状态组件
- 根据组件的不同职责,可以分为:展示型组件和容器型组件
// 类组件
class App extends React.Component {
constructor(){
super()
this.state = {
message: "class component"
}
}
render(){
const { message } = this.state
/**
* render返回值
* 1. react元素:通过jsx编写的代码会被编译成React.createElement
* 2. 组件或者fragments
* retrun ["abc","acc"]
* return [
* <h1>元素</h1>
* ]
* 3. Portals:可以渲染子节点到不同的DOM子树中
* 4. 字符串或者数值类型
* 5. 布尔值或者null:什么都不渲染
*/
return <h1>{message}</h1>
}
}
// 函数组件
function App(){
/**
* 返回值和类组件一致
* 没有自己的生命周期
* 没有this
* 没有构造器没有state
*/
return <h1>function Component</h1>
}
export default App;
父子组件传值
// 类组件传值
// 父组件
class App extends React.Component {
constructor(){
super()
this.state = {
message: "class component"
}
}
resetMsg(msg){
this.setState({
message: msg
})
}
render(){
let { message } = this.state
return (
<div>
<Header></Header>
// 父组件传递message和函数resetMsg 给子组件,
// 子组件展示 message并通过resetMsg函数通知父组件修改resetMsg的值
<Main message={message} resetMsg={(msg) => {this.resetMsg(msg)}}></Main>
<Footer></Footer>
</div>
)
}
}
// 子组件
export class Main extends Component {
updateMsg(){
// 通过resetMsg回传通知父组件修改数据
this.props.resetMsg('now updateMsg')
}
render() {
return (
<div onClick={() => {this.updateMsg()}}>
<h1>{ this.props.message }</h1>
Main
</div>
)
}
}
export default Main
类似vue 插槽做法
// 父组件
render(){
let { message } = this.state
return (
<div>
<Header></Header>
<Main message={message} resetMsg={(msg) => this.resetMsg(msg)}></Main>
// 方案一: 将子元素直接写在父元素内
<Footer>
<h3>底部第一个元素</h3>
<h3>底部第二个元素</h3>
<h3>底部第三个元素</h3>
</Footer>
// 方案一: 将子元素直接写在父元素内
<Footer
FirstSlot={
<h3>底部第一个元素</h3>
}
// 可设置动态作用域插槽 通过子组件传入item展示
SecSlot={
item => <h3>{ item }</h3>
}
></Footer>
</div>
)
}
// Footer.jsx
import React, { Component } from 'react'
export class Footer extends Component {
render() {
/**
* 方案一:可通过this.props.children 直接获取到内部的三个子元素
* 注意:当父元素内只包含一个元素时 是直接通过{ children }获取而不是{ children[0] }
* 方案二: 可通过this.props直接获取子元素
*/
const { children } = this.props
const { FirstSlot,SecSlot } = this.props
return (
<div>
<h1>Footer</h1>
{ children[0] }
{ children[1] }
{ children[2] }
{ FirstSlot }
{ SecSlot("底部第二个元素") }
</div>
)
}
}
export default Footer