简体   繁体   中英

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.

How this is possible and how it works? does this work because component is also object of javascript?

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. 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.

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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