组件跨层级通信 - Context
上下文提供一种不需要每层设置props就能跨多级组件传递数据的方式
方式1
Provider提供值 Consumer来消费传递的值
import React from 'react' ;
const Mycontext = React. createContext ( ) ;
const { Provider, Consumer } = MyContext; function Child ( prop) { return < div> Child: { prop. foo} < / div>
} export default function ContextTest ( ) { return ( < div> < Provider value = { { foo: 'bar' } } > < Consumer> { value => < Child { ... child} / > } < / Consumer> < / Provider> < / div> )
}
方式2
import React, { useContext} from 'react' ;
const { Provider } = MyContext; const MyContext = React. createContext ( ) ;
function Child2 ( ) { const ctx = useContext ( MyContext) ; return < div> Child2: { ctx. foo} < / div>
} export default function ContextTest ( ) { return ( < div> < Provider value= { { foo: 'bar' } } > < Child2> < / Child2> < / Provider> < / div> )
}
方式3
import React from 'react'
const MyContext = React. createContext ( ) ; class Child3 extends React. Component { static contextType = MyContext; render ( ) { return < div> Child3: { this . context. foo} < / div> }
} export default function ContextTest ( ) { return ( < div> < Provider value= { { foo: 'bar' } } > < Child3> < / Child3> < / Provider> < / div> )
}