From d8892820e61ded72f9cdaa39ff0a1f0347a54dff Mon Sep 17 00:00:00 2001
From: shikong <919411476@qq.com>
Date: Sun, 27 Oct 2024 20:22:03 +0800
Subject: [PATCH] =?UTF-8?q?10.=20ref=20=E4=B8=8E=20context?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/components/GrandSonComponent.js | 25 +++++++++++++++++++++++++
src/components/SonComponent.js | 22 +++++++++++++++++++++-
2 files changed, 46 insertions(+), 1 deletion(-)
create mode 100644 src/components/GrandSonComponent.js
diff --git a/src/components/GrandSonComponent.js b/src/components/GrandSonComponent.js
new file mode 100644
index 0000000..bf61ca6
--- /dev/null
+++ b/src/components/GrandSonComponent.js
@@ -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 (
+
+ GrandsonComponent 组件
+
+
+ {
+ (value) => {
+ return
+ Context.Consumer
+
+ ({value.msg})
+
+
+ }
+ }
+
+
+
)
+ }
+}
diff --git a/src/components/SonComponent.js b/src/components/SonComponent.js
index 7ee82d6..870b66f 100644
--- a/src/components/SonComponent.js
+++ b/src/components/SonComponent.js
@@ -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
子组件
-
+
{this.state.msg}
@@ -111,6 +126,11 @@ export default class SonComponent extends React.Component {
+
+ {/* 只有 value 一个 props, 如果要传递多个参数则使用对象 */}
+
+
+
}
}