我正在开发的仪表板 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/