💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 数据传输方式 props与redux不详细说了。主要看一下context api ## context api ~~~ // Context lets us pass a value deep into the component tree // without explicitly threading it through every component. // Create a context for the current theme (with "light" as the default). const ThemeContext = React.createContext('light'); class App extends React.Component { render() { // Use a Provider to pass the current theme to the tree below. // Any component can read it, no matter how deep it is. // In this example, we're passing "dark" as the current value. return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); } } // A component in the middle doesn't have to // pass the theme down explicitly anymore. function Toolbar(props) { return ( <div> <ThemedButton /> </div> ); } function ThemedButton(props) { // Use a Consumer to read the current theme context. // React will find the closest theme Provider above and use its value. // In this example, the current theme is "dark". return ( <ThemeContext.Consumer> {theme => <Button {...props} theme={theme} />} </ThemeContext.Consumer> ); } ~~~ 1. 首先通过React.createContext创建context,同时传入默认值'light' 2. 使用Provider将context定义的prop值向下传输,在上面例子中可以看到,使用这个方法后,Toolbar就不需要再在标签中接收props了 3. 在需要接收props的组件中,使用Consumer,通过函数的形式接收到theme值。在上面例子中就是'dark'