我正在使用通过上下文传递的函数。
ChildComponent.contextType = SomeContext;
现在,我使用this.context.someFunction();
。这行得通。
如果我需要来自两个不同父级组件的函数怎么办?
答案 0 :(得分:13)
您仍可以通过16.3上下文API使用子级功能消费者节点,这就是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>
);
}
要在组件的上下文中使用函数,通常将组件包装在HOC中,以便将上下文作为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)
答案 1 :(得分:8)
另一种解决方案是创建一个单独的上下文,以提供其他上下文:
import React, { createContext, memo, useContext } from "react";
import isEqual from "react-fast-compare";
export const MultiContext = createContext(null);
MultiContext.displayName = "MultiContext";
export const MultiContextProvider = memo(
function({ map, children }) {
const contextMap = {};
for (const i in map) {
contextMap[i] = useContext(map[i]);
}
return (
<MultiContext.Provider value={contextMap}>
{children}
</MultiContext.Provider>
);
},
(prevProps, nextProps) => isEqual(prevProps.children, nextProps.children)
);
MultiContextProvider.displayName = "MultiContextProvider";
用法示例:
class DemoConsumer extends React.Component {
static contextType = MultiContext;
render() {
return JSON.stringify({
someValue: this.context.SomeContext.someValue,
otherValue: this.context.OtherContext.otherValue,
});
}
}
function App() {
return (
<MultiContextProvider map={{ SomeContext, OtherContext }}>
<MultiContextDemoClassConsumer />
</MultiContextProvider>
);
}
演示:
const {
createContext,
memo,
useContext,
useState,
useEffect,
} = React;
const MultiContext = createContext(null);
MultiContext.displayName = "MultiContext";
const MultiContextProvider = memo(
function({ map, children }) {
console.log("render provider");
const contextMap = {};
for (const i in map) {
contextMap[i] = useContext(map[i]);
}
return (
<MultiContext.Provider value={contextMap}>
{children}
</MultiContext.Provider>
);
},
(prevProps, nextProps) => isEqual(prevProps.children, nextProps.children)
);
MultiContextProvider.displayName = "MultiContextProvider";
const initialMinutes = new Date().getMinutes();
const MinutesContext = createContext(initialMinutes);
MinutesContext.displayName = "MinutesContext";
const IncrementContext = createContext(0);
IncrementContext.displayName = "IncrementContext";
class MultiContextDemoClassConsumer extends React.Component {
static contextType = MultiContext;
render() {
return JSON.stringify(this.context);
}
}
const multiContextMap = { MinutesContext, IncrementContext };
function App() {
const forceUpdate = useForceUpdate();
const [minutes, setMinutes] = useState(initialMinutes);
useEffect(() => {
const timeoutId = setInterval(() => {
// console.log('set minutes')
setMinutes(new Date().getMinutes());
}, 1000);
return () => {
clearInterval(timeoutId);
};
}, [setMinutes]);
const [increment, setIncrement] = useState(0);
console.log("render app");
return (
<MinutesContext.Provider value={minutes}>
<IncrementContext.Provider value={increment}>
<MultiContextProvider map={multiContextMap}>
<MultiContextDemoClassConsumer />
</MultiContextProvider>
<button onClick={() => setIncrement(i => i + 1)}>Increment</button>
<button onClick={forceUpdate}>Force Update</button>
</IncrementContext.Provider>
</MinutesContext.Provider>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script type="module">
import React from 'https://dev.jspm.io/react@16';
import ReactDOM from 'https://dev.jspm.io/react-dom@16';
import useForceUpdate from 'https://dev.jspm.io/use-force-update@1.0.7';
import isEqual from 'https://dev.jspm.io/react-fast-compare@3.0.1';
window.React = React;
window.ReactDOM = ReactDOM;
window.useForceUpdate = useForceUpdate.default;
window.isEqual = isEqual;
</script>
<div id="root"></div>
答案 2 :(得分:4)
您还可以将所有上下文简单地合并为一个上下文:
const AppContext = React.createContext({
user: { name: 'Guest' },
theme: 'light',
})
ChildComponent.contextType = AppContext;
完成。如果您在应用的某些部分具有不同的上下文(例如,不同的主题或用户),则只需合并新值即可。