react生命周期+组件传参

组件传参

父传子

// 1. 类式组件
class ComC extends React.Component {
	render() {
		return (
			{/* 类式组件通过 `this.props.xx`获取参数 */}
			<div>{this.props.title}</div> 
		)
	}
}

// 2.函数式组件
function ComF(props) {
	return (
		// 函数式组件,通过 函数入参 传递参数
		<div>{props.title}</div>
	)
}

class App extends React.Component {
	render (){
		return (
			<ComC title="这是类式组件"/>
			<ComF title="这是函数式组件"/>
		)
	}
}
1. props是只读对象(readOnly)
根据单向数据流的要求,子组件只能读取props的数据,不能修改。

2. props可以传递任意数据
数字、字符串、数组、对象、布尔、函数、jsx

子传父

function Son(props){
	const {handler} = props;

	return (
		<button onClick={() => handler('子组件传递给父组件的值')}></button>
	)
}

class App extends React.Component {
	handler = (text) => {
		console.log(text);
	}
	
	render(){
		return (
			<Son handler={handler} />
		)
	}
}
子组件调用父组件传递过来的函数,将要传递的数据作为实参传入该函数即可。

函数组件 使用 createContext 创建 Context 对象 在顶层组件通过 Provider 提供数据
在底层组件通过useContext 函数获取数据

import React, {useState, createContext, useContext} from "react";

// 1. 通过createContext 构造 Context 对象
const Context = createContext();

function SonB() {
  const count = useContext(Context);

  return (
    <div>
      This is SonB, count is {count}
    </div>
  )
}

function SonA() {
  // 3.在底层组件中使用 useContext() 获取数据
  const count = useContext(Context);

  return (
    <div>
      This is SonA, count is {count}
      <SonB></SonB>
    </div>
  )
}

function App() {
  const [count, setCount] = useState(10);

  return (
    <Context.Provider value={count}>
      {/* 2.在顶层组件使用 Context.Provider 提供数据 */}
      <div>
        <button onClick={() => setCount(100)}>change{count}</button>
        <SonA ></SonA>
      </div>
    </Context.Provider>
  )
}


react生命周期

在这里插入图片描述
总结:

1.初始化阶段: 由ReactDOM.render()触发—初次渲染

  1. constructor() —构造器
  2. componentWillMount() —将要挂载
  3. render() —render
  4. componentDidMount() —挂载时 更新阶段: 由组件内部

2.this.setSate()或父组件重新render触发

  1. shouldComponentUpdate() —是否要进行更改数据
  2. componentWillUpdate() —将要更新数据
  3. render()
  4. componentDidUpdate() —更新数据
  1. 卸载组件: 由ReactDOM.unmountComponentAtNode()触发

componentWillUnmount() —卸载

4.初始化阶段: 由ReactDOM.render()触发—初次渲染

  1. constructor()
  2. getDerivedStateFromProps
  3. render()
  4. componentDidMount()

5.更新阶段: 由组件内部this.setSate()或父组件重新render触发

  1. getDerivedStateFromProps
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate
  5. componentDidUpdate()

6.卸载组件: 由ReactDOM.unmountComponentAtNode()触发

componentWillUnmount()

重要的钩子:

1.render:初始化渲染或更新渲染调用
2.componentDidMount:开启监听, 发送ajax请求
3.componentWillUnmount:做一些收尾工作, 如: 清理定时器
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值