[react] 怎么使用Context开发组件?
import React, {Component} from 'react'// 首先创建一个 context 对象这里命名为:ThemeContext
const ThemeContext = React.createContext('light')// 创建一个祖先组件组件 内部使用Provier 这个对象创建一个组件 其中 value 属性是真实传递的属性
class App extends Component {render () {return (<ThemeContext.Provider value="dark"><Toolbar /></ThemeContext.Provider>)}
}// 渲染 button 组件的外层包裹的属性
function Toolbar () {return (<div><ThemeButton /></div>)
}
// 在 Toolbar 中渲染的button 组件 返回一个 consumer (消费者)将组件组件的 value 值跨组件传递给 // ThemeButton 组件
function ThemeButton (props) {return (<ThemeContext.Consumer>{ theme => <button {...props} theme={theme}>{theme}</button> }</ThemeContext.Consumer>)
}
个人简介
我是歌谣,欢迎和大家一起交流前后端知识。放弃很容易,
但坚持一定很酷。欢迎大家一起讨论
主目录
与歌谣一起通关前端面试题