ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
context: 实现跨层级的组件数据传递 ``` import React, { createContext } from 'react'; import logo from './logo.svg'; // 1. 引入 createContext() const BatteryContext = createContext(); function Leaf() { return ( // 数据消耗者 <BatteryContext.Consumer> { battery => <h1>Battery: {battery}</h1> } </BatteryContext.Consumer> ) } function Middle() { return ( <Leaf /> ) } class App extends React.Component { state = { battery: 60 } render() { const {battery} = this.state return ( // 数据提供者 <BatteryContext.Provider value={battery}> <button type="button" onClick={()=>this.setState({battery:50})}>点击</button> <Middle /> </BatteryContext.Provider> ) } } export default App; ```