开发中有时候会遇到跨组件通信,这里介绍两种方法
方法一:
那就是一层层传递了,下面这个案例就把爷爷组件里面的数据传递到孙子组件里面
定义一个"爷爷组件"
export default class App extends Component {
constructor(props){
super(props);
this.state ={
nickName :"lsh",
age :18
}
}
render() {
return (
<div>
<Profile {...this.state}></Profile>
</div>
)
}
}
定义一个"父组件"
function Profile(props){
return (
<div>
<ProfileHeader {...props}></ProfileHeader>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
)
}
定义一个"孙组件"
function ProfileHeader(props) {
return (
<div>
<h2>用户昵称:{props.nickName}</h2>
<h2>用户等级:{props.age}</h2>
</div>
)
}
方法二
通过context可以实现
我们要先const一个context
const Usercontext = React.createContext({
// nickName:'ls',
// age:18
// 默认值,可以不写
})
“爷爷组件”
export default class App extends Component {
constructor(props){
super(props);
this.state ={
nickName :"lsh",
age :20
}
}
render() {
return (
<div>
<Usercontext.Provider value={this.state}>
<Profile/>
</Usercontext.Provider>
</div>
)
}
}
需要用一个Usercontext.Provider把"父组件"包裹起来,value里面就放我们需要传递的数据
“父组件”
function Profile(){
return (
<div>
<ProfileHeader></ProfileHeader>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
)
}
“孙组件”
分有两种情况
当"孙组件"为类组件时候
ProfileHeader.contextType =Usercontext
class ProfileHeader extends Component{
render(){
return (
<div>
<h2>用户昵称:{this.context.nickName}</h2>
<h2>用户等级:{this.context.age}</h2>
</div>
)
}
}
当"孙组件"为函数式组件时候
function ProfileHeader() {
return (
<Usercontext.Consumer>
{
value =>{
return (
<div>
<h2>用户昵称:{value.nickName}</h2>
<h2>用户等级:{value.age}</h2>
</div>
)
}
}
</Usercontext.Consumer>
)
}
如果有多个context的时候,我们怎么做呢??
那我们就需要const多个context了,下面来举个例子
const Usercontext = React.createContext({
})
const ThemeContext = React.createContext({
color: 'red'
})
“爷组件”
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
nickName: "lsh",
age: 20
}
}
render() {
return (
<div>
<Usercontext.Provider value={this.state}>
<ThemeContext.Provider value={{ color: 'red' }}>
<Profile />
</ThemeContext.Provider>
</Usercontext.Provider>
</div>
)
}
}
“父组件”
function Profile(props) {
return (
<div>
<ProfileHeader></ProfileHeader>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
)
}
“孙组件”
function ProfileHeader() {
return (
<Usercontext.Consumer>
{
value => {
return (
<ThemeContext.Consumer>
{
theme => {
return (
<div>
<h2 style={{color:theme.color}}>用户昵称:{value.nickName}</h2>
<h2>用户等级:{value.age}</h2>
<h2>颜色:{theme.color}</h2>
</div>
)
}
}
</ThemeContext.Consumer>
)
}
}
</Usercontext.Consumer>
)
}
当有多个context时候,就得一层层嵌套了