javascript - 如何嵌套 React 组件/模块来分离 UI?

标签 javascript reactjs react-dom

我正在开发的仪表板 UI 有三个主要组件(我是 React 初学者,来自 Angular):侧边栏、顶部导航和内容容器。

我如何将它们分成三个独立的 UI 组件并在其他组件中调用它们?我希望能够做到这一点:

<Sidenav /> <!-- sidenav component from Sidenav.js -->
<section className="content">
    <Topnav /> <!-- top nav component from Topnav.js -->
    <div className="wrapper container">
        <!-- Content here -->
    </div>
</section>

此外,您将如何使用 <div className="wrapper container"></div>作为所有内容的 View ?

我正在使用 ES6 和 React Starterify应用程序套件。

最佳答案

这就是我的做法(您会注意到我将所有组件文件命名为 .jsx 而不是 .js,尽管这两种方式都没关系.我什至见过人们这样做 Component.jsx.js):

src/index.html

<html>
  <head>
    ...
  </head>
  <body>
    <script src="js/bundle.min.js"></script> <!-- I'm assuming you're using Browserify or similar to bundle the entire app into a single file -->
  </body>
</html>

src/js/main.js

import React from 'react';
import {render} from 'react-dom';
import {Routes} from '../components';

render(Routes, document.body);

src/components/App.jsx

import React from 'react';
import Topnav from './Topnav';

module.exports = React.createClass({
  displayName: 'App',
  propTypes: {
    children: React.PropTypes.shape({
      props: React.PropTypes.object
    })
  },
  render () {
    return (
      <section className="content">
        <Topnav />
        <div className="wrapper container">
          {this.props.children}
        </div>
      </section>
    );
  }
});

{this.props.children} 将渲染正在处理当前路由的组​​件。

src/components/Topnav.jsx

...

将其视为在面向对象语言(如 Java)中创建分组的相同方式。彼此所属的组件应该放在一起。因此,例如,如果我必须编写一个 Profile 组件,则可能如下所示:

-- src
  -- components
    -- profile
      -- index.js // Used to export Profile 
      -- Profile.jsx // This would have the profile layout and be a parent to all other components in this folder
      -- Address.jsx
      -- Gravatar.jsx
      -- ...

关于javascript - 如何嵌套 React 组件/模块来分离 UI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34907040/

相关文章:

reactjs - 如何使用 Hooks API 在 React 中避免不必要的渲染

javascript - jQuery 动态添加 javascripts 标签关闭按钮

javascript - 如何在不刷新浏览器或在 React 中使用 useEffect 的情况下检测服务器数据变化?

javascript - React.js 未捕获错误 : Invariant Violation updating list

javascript - 这个 redux Action 和 reducer 有什么问题?

javascript - 我如何将 html 标签数组添加到 jsx

javascript - 使用 React refs 的 scrollIntoView

javascript - _.invoke 方法在 Lodash 中如何工作?

javascript - 如果值存在,如何避免将字段设置为空字符串

javascript - npm start 在 cmd 中不起作用,并且显示错误,如图所示?