10. ref 与 context

This commit is contained in:
shikong 2024-10-27 20:22:03 +08:00
parent 4a9c9e3516
commit d8892820e6
Signed by: Shikong
GPG Key ID: BD85FF18B373C341
2 changed files with 46 additions and 1 deletions

View File

@ -0,0 +1,25 @@
import React from "react"
import SonComponentCss from "./SonComponent.module.css";
import {Context} from "./SonComponent"
export default class GrandsonComponent extends React.Component {
render(){
return (<div className={SonComponentCss.children}>
<div>
GrandsonComponent 组件
<Context.Consumer>
{
(value) => {
return <div className={SonComponentCss.children}>
Context.Consumer
<div>
(<span>{value.msg}</span>)
</div>
</div>
}
}
</Context.Consumer>
</div>
</div>)
}
}

View File

@ -2,6 +2,12 @@ import React from "react";
import PropTypes from "proptypes"
// 模块化 css, 后缀 .module.css
import SonComponentCss from "./SonComponent.module.css"
import GrandsonComponent from "./GrandSonComponent";
// 类似于 vue 中的 provider + inject
export let Context = React.createContext({})
// let divRef = React.createRef()
export default class SonComponent extends React.Component {
state = {
msg: "SonComponent Msg",
@ -9,6 +15,8 @@ export default class SonComponent extends React.Component {
childrenClass: []
}
divRef = React.createRef()
constructor(props) {
super(props);
console.log("[constructor] SonComponent")
@ -18,6 +26,13 @@ export default class SonComponent extends React.Component {
componentDidMount() {
this.changeChildrenClass()
console.log('[挂载] SonComponent 组件后执行的操作');
// 废弃
// 旧版本写法
// console.log(this.refs.devRef)
// console.log("divRef", divRef, divRef.current)
console.log("divRef", this.divRef, this.divRef.current)
}
// 优化生命周期
@ -83,7 +98,7 @@ export default class SonComponent extends React.Component {
return <div style={{border: '1px solid', width: '80%', overflow: 'auto'}}>
子组件
<div>
<div ref={this.divRef}>
{this.state.msg}
</div>
@ -111,6 +126,11 @@ export default class SonComponent extends React.Component {
<button onClick={this.switchChildrenBorder}>切换边框显示</button>
</div>
</div>
{/* 只有 value 一个 props, 如果要传递多个参数则使用对象 */}
<Context.Provider value={{msg: "从父组件传递的消息"}}>
<GrandsonComponent/>
</Context.Provider>
</div>
}
}