我正在阅读教程:
https://www.robinwieruch.de/gentle-introduction-higher-order-components/
他们有这样的陈述:
const withTodosNull = (Component) => (props) =>
!props.todos
? null
: <Component { ...props } />
据我所知,Component
被传递给函数,然后它的props
被隐式获取并输入到返回函数中。我不明白React
是怎么做的。老实说,我会期待像(Component) => (Component.props)
这样的东西。这个机制是什么?只有当我们将参数提供为props
或者我们可以提供任何名称时,它是否正确映射?这种隐式赋值是否有特定的名称?
更新
也许我不够清楚,但我真正感兴趣的是props
在内部函数中出现的地方,如果它们没有传递给前一个外部函数。我理解HOC是如何工作的,如何思考它们,但这个时刻非常不清楚,React
在做什么呢?是否有某种engine
在幕后运行,idk ...
这种技术称为higher-order components(HOCs),是一种通过一些额外功能扩展组件的方法。
如果使用常规函数而不是箭头函数重写它,它可能看起来更容易:
function withTodosNull(Component) {
return function(props) {
if (!props.todos) {
return null;
} else {
return <Component {...props} />
}
}
}
withTodosNull
接受一个组件并返回一个新组件。如果返回的这个新组件获得todos
prop,则传递到HOC的组件将使用所有props呈现。如果没有给出todos
作为道具,那么将呈现null
。
如果我们使用经典的function()
重写箭头函数,可能会更容易理解:
function withTodosNull(Component) {
return function(props) {
if (!props.todos) {
return null;
}
return <Component {...props} />;
}
}
内部未命名函数是一个功能组件。它需要属性并呈现为null
或Component
。
外部函数称为高阶分量(HoC)。它是一个函数,它包装一个组件并返回一个新组件。
Component
和props
之间没有联系。它们只是两个不同功能的参数。
具体来说,当你打电话:
class MyComponent: React.Component {
}
const myComponentWithTodosNull = withTodosNull(MyComponent);
它与写作相同:
const myComponentWithTodosNull = props => {
if (!props.todos) {
return null;
}
return <MyComponent {...props} />;
}
高阶组件是“增强”作为参数传递的组件的函数。要了解道具的来源,让我们看看使用这样的组件会是什么样子。
我们的基本组件将传递给HoC:
function TodoList(props) {
return (
<div>We have {props.todos.length} tasks to do!</div>
);
}
现在,我们可以使用我们的HoC创建新的“增强”组件,当没有任何任务时,它会阻止显示此消息:
const EnhancedTodoList = withTodosNull(TodoList);
然后我们可以使用这个新组件来呈现消息(如果没有任何任务,则不使用):
<EnhancedTodoList todos={someTodos} />
正如你所看到的,EnhancedTodoList
是第一个获得todos
的组件。然后它决定是否应该将道具传递给TodoList
,或者当没有任何待办事项时它应该返回null
。
Todos明确地从呈现HoC的组件传递。 EnhancedTodoList
就像TodoList
的过滤器一样。