10. ref 与 context
This commit is contained in:
parent
4a9c9e3516
commit
d8892820e6
25
src/components/GrandSonComponent.js
Normal file
25
src/components/GrandSonComponent.js
Normal 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>)
|
||||
}
|
||||
}
|
@ -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>
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user