反应多个上下文 [英] React multiple contexts

查看:31
本文介绍了反应多个上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用通过上下文传递的函数.

ChildComponent.contextType = SomeContext;

现在我使用this.context.someFunction();.这有效.

如果我需要来自两个不同父组件的函数,我该怎么做?

解决方案

您仍然可以将 function-as-a-child 消费者节点与 16.3 Context API 一起使用,这就是 React 文档建议这样做:

//主题上下文,默认为浅色主题const ThemeContext = React.createContext('light');//登录的用户上下文const UserContext = React.createContext({name: '客人',});类 App 扩展了 React.Component {使成为() {const {signedInUser, theme} = this.props;//提供初始上下文值的应用程序组件返回 (<ThemeContext.Provider value={theme}><UserContext.Provider value={signedInUser}><布局/></UserContext.Provider></ThemeContext.Provider>);}}功能布局(){返回 (<div><侧边栏/><内容/>

);}//一个组件可以使用多个上下文功能内容(){返回 (<ThemeContext.Consumer>{主题=>(<UserContext.Consumer>{用户=>(<ProfilePage user={user} theme={theme}/>)}</UserContext.Consumer>)}</ThemeContext.Consumer>);}

要在组件的上下文中使用函数,您通常会将组件包装在 HOC 中,以便将上下文作为 props 传入:

export const withThemeContext = Component =>(道具 =>(<ThemeContext.Consumer>{上下文=><组件 themeContext={context} {...props}/>}</ThemeContext.Consumer>))const YourComponent = ({ themeContext, ...props }) =>{themeContext.someFunction()return (<div>妈妈!</div>)}导出默认 withThemeContext(YourComponent)

如果您运行的是 React 16.8+,您还可以使用钩子更干净地完成此操作,而无需使用 HOC:

import React, { useContext } from "react"const YourComponent = props =>{const 主题 = useContext(ThemeContext)const user = useContext(UserContext)}

或者,如果你经常使用这些上下文,你甚至可以制作一个自定义钩子来进一步简化:

const useTheme = () =>使用上下文(主题上下文)const useUser = () =>使用上下文(用户上下文)const YourComponent = props =>{const 主题 = useTheme()const user = useUser()}

I am using functions which are passed down through context.

ChildComponent.contextType = SomeContext;

Now I use this.context.someFunction();. This works.

How can I do this if I need functions from two different parent components?

解决方案

You can still use function-as-a-child consumer nodes with the 16.3 Context API, which is what the React documentation suggests doing:

// Theme context, default to light theme
const ThemeContext = React.createContext('light');

// Signed-in user context
const UserContext = React.createContext({
  name: 'Guest',
});

class App extends React.Component {
  render() {
    const {signedInUser, theme} = this.props;

    // App component that provides initial context values
    return (
      <ThemeContext.Provider value={theme}>
        <UserContext.Provider value={signedInUser}>
          <Layout />
        </UserContext.Provider>
      </ThemeContext.Provider>
    );
  }
}

function Layout() {
  return (
    <div>
      <Sidebar />
      <Content />
    </div>
  );
}

// A component may consume multiple contexts
function Content() {
  return (
    <ThemeContext.Consumer>
      {theme => (
        <UserContext.Consumer>
          {user => (
            <ProfilePage user={user} theme={theme} />
          )}
        </UserContext.Consumer>
      )}
    </ThemeContext.Consumer>
  );
}

To use functions in context in your component you'd typically wrap your component in a HOC so the context is passed in as props:

export const withThemeContext = Component => (
  props => (
    <ThemeContext.Consumer>
      {context => <Component themeContext={context} {...props} />}
    </ThemeContext.Consumer>
  )
)

const YourComponent = ({ themeContext, ...props }) => {
  themeContext.someFunction()
  return (<div>Hi Mom!</div>)
}

export default withThemeContext(YourComponent)

If you're running React 16.8+ you can also use hooks to do this more cleanly without using HOCs:

import React, { useContext } from "react"

const YourComponent = props => {
  const theme = useContext(ThemeContext)
  const user = useContext(UserContext)
}

Or, if you consume these contexts a lot, you can even make a custom hook to simplify further:

const useTheme = () => useContext(ThemeContext)
const useUser = () => useContext(UserContext)

const YourComponent = props => {
  const theme = useTheme()
  const user = useUser()
}

这篇关于反应多个上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆