组件传参
父传子
// 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()触发—初次渲染
- constructor() —构造器
- componentWillMount() —将要挂载
- render() —render
- componentDidMount() —挂载时 更新阶段: 由组件内部
2.this.setSate()或父组件重新render触发
- shouldComponentUpdate() —是否要进行更改数据
- componentWillUpdate() —将要更新数据
- render()
- componentDidUpdate() —更新数据
- 卸载组件: 由ReactDOM.unmountComponentAtNode()触发
componentWillUnmount() —卸载
4.初始化阶段: 由ReactDOM.render()触发—初次渲染
- constructor()
- getDerivedStateFromProps
- render()
- componentDidMount()
5.更新阶段: 由组件内部this.setSate()或父组件重新render触发
- getDerivedStateFromProps
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate
- componentDidUpdate()
6.卸载组件: 由ReactDOM.unmountComponentAtNode()触发
componentWillUnmount()
重要的钩子:
1.render:初始化渲染或更新渲染调用
2.componentDidMount:开启监听, 发送ajax请求
3.componentWillUnmount:做一些收尾工作, 如: 清理定时器