也许最简单的方法是描述一个类似的概念:函数装饰器。
// Start with a function, any function.
let add = (a, b) => a + b;
但是现在我们要为参数添加日志并返回:
let addWithLogging = (a, b) => {
console.log("Args are ", a, b);
const result = a + b;
console.log("Result is ", result);
return result;
}
但是等等,这是JavaScript,我们有更高阶的函数,可以提取一个decorator:
// Here we take a function f and wrap it. We'll return a function that will
// collect the arguments, log them, perform f on them, log the result, and
// then finally return that result to the caller.
const withLogging = f => (...args) => {
console.log("Args are ", ...args);
const result = f(...args);
console.log("Result is ", result);
return result;
};
addWithLogging = withLogging(add);
你呢
只需将UserContext组件作为另一个组件返回的JSX的一部分:
const UserAvatar = ({ user, size }) => (
<UserContext.Consumer>
<img
className={`user-avatar ${size || ""}`}
alt="user avatar"
src={user.avatar}
/>
</UserContext.Consumer>
);
但是现在,就像在日志示例中一样,您在每个需要它的组件中重复样板文件。
user
已经在
props
渲染组件时。供参考,以下是
compiled JSX
.
应该仔细阅读代码。
用户
通过上下文提供程序进行注入,唯一的方法是为它提供一个传递参数的函数。