【问题标题】:react higher order component反应高阶成分
【发布时间】:2018-06-10 08:54:56
【问题描述】:

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

说我有以下功能:

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(如果它是类组件)。

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    高阶组件返回一个函数,它是一个函数组件。我认为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>
    );
    

    【讨论】:

      猜你喜欢
      • 2017-10-18
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 2020-08-22
      • 2017-09-02
      • 1970-01-01
      • 2017-02-16
      相关资源
      最近更新 更多