1. 隔代组件传值
1.1 props传递
传递方式:通过props属性自上而下逐层传递
存在问题:层级过多导致传值繁琐
import React from 'react'
//父组件
class App extends React.Component{
render(){
return (
//1.传递value值
<Demo1 value="hello hello"/>
)
}
}
//中间组件
class Demo1 extends React.Component{
render(){
return (
//2.中间组件帮助传递value值
<Demo2 value={this.props.value} />
)
}
}
//子组件
class Demo2 extends React.Component{
render(){
return (
//3.接收value值
<h1>{this.props.value}</h1>
)
}
}
export default App
1.2 Context传递
传递方式:类似于全局变量
存在问题:组件复用性较差
使用方法:
- 创建Context(ValueContext可任意命名)
const ValueContext = React.createContext('') //默认值为''
- 用ValueContext.Provider包裹组件树中的根节点,并传递
value
值
<ValueContext.Provider value="hello hello">
- 此时,该组件树中的节点均能访问到步骤2中根节点所传递的
value
值
3.1 指定contextType读取当前的ValueContext
static contextType = ValueContext
3.2 读取value值
this.context
import React from 'react'
//1.创建一个Context
const ValueContext = React.createContext('') //默认值为''
//父组件
class App extends React.Component{
render(){
return (
//2.用ValueContext.Provider包裹组件树中的根节点
//传递value值为"hello hello"
//组件树中的节点均能访问到该value值
<ValueContext.Provider value="hello hello">
<Demo1/>
</ValueContext.Provider>
)
}
}
//中间组件
class Demo1 extends React.Component{
//指定contextType读取当前的ValueContext
static contextType = ValueContext
render(){
return (
//this.context即父组件中传递的"hello hello"
<div>
<h1>{this.context}</h1>
<Demo2/>
</div>
)
}
}
//子组件
class Demo2 extends React.Component{
//指定contextType读取当前的ValueContext
static contextType = ValueContext
render(){
return (
//this.context即父组件中传递的"hello hello"
<h2>{this.context}</h2>
)
}
}
export default App
效果图: