简体   繁体   English

点符号如何在 React.js 的功能组件中工作?

[英]How dot notation works in functional component of React.js?

While I was searching article about compound component pattern, I have found out that accessing sub-component through dot notation is possible like javascript object.在搜索有关复合组件模式的文章时,我发现可以通过点符号访问子组件,例如 javascript object。

How this is possible and how it works?这怎么可能以及它是如何工作的? does this work because component is also object of javascript?这是否有效,因为组件也是 javascript 的 object?

const App = () => (
  <Menu>
    <Menu.Item>Home</Menu.Item>
    <Menu.Item>Blog</Menu.Item>
    <Menu.Item>About</Menu.Item>
  </Menu>
);

This is accomplished my simply attaching the compound component as a property to the parent component.这是通过简单地将复合组件作为属性附加到父组件来完成的。

Attaching is how you keep the nested compound component with its parent component.附加是您如何将嵌套的复合组件与其父组件保持在一起。 The alternative is to export Item separately, and then also import it separately.另一种方法是单独导出Item ,然后也单独导入。 In many cases the nested child component is only valid as a direct descendent of the parent component, consuming a context, or being informed how to "layout" in the DOM.在许多情况下,嵌套子组件作为父组件的直接后代有效,使用上下文或被告知如何在 DOM 中“布局”。

Example:例子:

const Menu = () => <div>Menu Component</div>
const Item = () => <div>Item Component</div>

Menu.Item = Item;

export default Menu;

Usage:用法:

import Menu from '../path/to/menu';

const App = () => (
  <Menu>
    <Menu.Item>Home</Menu.Item>
    <Menu.Item>Blog</Menu.Item>
    <Menu.Item>About</Menu.Item>
  </Menu>
);

Demo演示

编辑如何点表示法工作在功能组件的反应js

Demo Code:演示代码:

const Menu = ({ children }) => (
  <div>
    <h1>Menu Component</h1>
    {children}
  </div>
);
const Item = ({ children }) => <div>{children}</div>;

Menu.Item = Item;

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <Menu>
        <Menu.Item>Home</Menu.Item>
        <Menu.Item>Blog</Menu.Item>
        <Menu.Item>About</Menu.Item>
      </Menu>
    </div>
  );
}

在此处输入图像描述

Question问题

Does this work because component is also object of javascript?这是否有效,因为组件也是 javascript 的 object?

No, not objects, but functional components (and class-based components) are transpiled into a regular javascript function invoked by the React framework, and as a variable reference you can attach properties to them.不,不是对象,而是功能组件(和基于类的组件)被转换为由 React 框架调用的常规 javascript function,并且作为变量引用,您可以将属性附加到它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM