[英]How do you nest React components/modules to separate the UI?
I have three main components for a dashboard UI I'm working on (I'm a React beginner, coming from Angular): a sidebar, top nav, and a content container. 我正在使用的仪表板UI有三个主要组件(我是来自Angular的React初学者):侧边栏,顶部导航和内容容器。
How would I split these into three separate UI components and call them in other components? 如何将它们分为三个独立的UI组件,并在其他组件中调用它们? I want to be able to do this: 我希望能够做到这一点:
<Sidenav /> <!-- sidenav component from Sidenav.js -->
<section className="content">
<Topnav /> <!-- top nav component from Topnav.js -->
<div className="wrapper container">
<!-- Content here -->
</div>
</section>
And also, how would you use the <div className="wrapper container"></div>
as a view for all content? 而且,您将如何使用<div className="wrapper container"></div>
作为所有内容的视图?
I'm using ES6 and the React Starterify app kit. 我正在使用ES6和React Starterify应用程序套件。
This is how I would do it (you'll notice I name all my component files .jsx
instead of .js
, though it doesn't matter either way. I've even seen people do Component.jsx.js
): 这就是我要这样做的方式(您会注意到我将所有组件文件都.jsx
为.jsx
而不是.js
,尽管这两种方式都没有关系。甚至我看到人们都在使用Component.jsx.js
):
src/index.html 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 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 SRC /组件/ 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}
will render the component that is handling the current route. {this.props.children}
将呈现正在处理当前路线的组件。
src/components/Topnav.jsx SRC /组件/ Topnav.jsx
...
Think of it the same way you would create grouping in an object-oriented language like Java. 可以像使用Java这样的面向对象语言创建分组的方式进行思考。 Components that belong with each other should go together. 彼此所属的组件应该一起使用。 So, for example, if I had to write a Profile
component, that might look like: 因此,例如,如果我必须编写一个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
-- ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.