gpt4 book ai didi

javascript - react 高阶成分

转载 作者:行者123 更新时间:2023-11-28 17:40:38 26 4
gpt4 key购买 nike

我正在研究高阶函数,但我不太明白这部分是如何工作的。

假设我有以下功能:

const withAdminWarning = WrappedComponent => {
return props => (
<div>
{props.isAdmin && <p>This is private info. Please dont share!</p>}
<WrappedComponent {...props} />
</div>
);
};


const Info = props => (
<div>
<h1>Info</h1>
<p>This info is: {props.info}</p>
</div>
);

const AdminInfo = withAdminWarning(Info);

ReactDOM.render(
<AdminInfo isAdmin={true} info="There are the details" />,
document.getElementById("app")
);

根据我对组件的理解,要访问 props 变量,如果它是无状态组件,则必须使用 props,如果它是类组件,则必须使用 this.props。

在上面的示例中, Prop 从哪里开始发挥作用,因为我无法从 WrappedComponent 或除了 return 语句之外的其他任何地方访问它。

最佳答案

高阶组件返回一个函数,该函数是一个函数组件。我认为 foo(Info) 意味着 withAdminWarning(Info) 是正确的吗?

因此,在调用 withAdminInfo 后,AdminInfo 组件基本上如下所示:

const AdminInfo = props => (
<div>
{props.isAdmin && <p>This is private info. Please dont share!</p>}
<div>
<h1>Info</h1>
<p>This info is: {props.info}</p>
</div>
</div>
);

关于javascript - react 高阶成分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030684/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com