4、通过content进行组件通信
https://reactjs.org/docs/context.html官网链接:
React官⽅⽂档中,Context被归类为⾼级部分(Advanced),
属于React的⾼级API,但官⽅并不建议在稳定版的App中使⽤ Context。
封装Appcontent.js方便其他组件调用: import React from 'react'; const Content =React.createContext(); export const Provider = Content.Provider; export const Consumer = Content.Consumer; App.js文件方法一: import React from 'react'; import './App.css'; import {Provider, Consumer}from './Appcontent' import Contents from './pages/Contents'; function App() { const state = { userInfo:'小明' } return ( <div className="App"> <Provider value={state}> <Consumer>{ctx=><Contents {...ctx} />}</Consumer> </Provider> </div> ); } export default App; 在组件中使用this.props获取: import React,{Component} from 'react' class Contents extends Component{ render(){ console.log(this.props) return( <div>Content</div> ) } } export default Contents;
App.js文件方法二:
import React from 'react';
import './App.css';
import {Provider}from './Appcontent'
import Contents from './pages/Contents';
function App() {
const state = {
userInfo:'小明'
}
return (
<div className="App">
<Provider value={state}>
<Contents />
</Provider>
</div>
);
}
export default App;
组件中传值:
import React,{Component} from 'react'
import {Consumer} from '../Appcontent'
class Contents extends Component{
render(){
console.log(this.props)
return(
<div>Content
<Consumer>{ctx=><TabBarHandle {...ctx} />}</Consumer>
</div>
)
}
}
export default Contents;
function TabBarHandle(prpos){
console.log(prpos);
return <div>TabBarHandle</div>
}