官术网_书友最值得收藏!

Reusing components

There's one more change I want to make before we finish up with our LoginContainer skeleton.

We talked earlier about making React components reusable, so you can implement the same code in multiple places in your application. We should try to split our UI into as many small and reusable pieces as possible to save us time, and I see a great candidate in our LoginContainer.

LoginContainer won't be our only container. In the next few chapters, we'll create new pages with different content, but we want them to have the same look, and we'll want to have the Chatastrophe logo and title at the top in the same place as it is now.

What I propose is that we make a new Header component that we can save for future use.

Now, we made our LoginContainer a class component because we needed to use state and methods. Our header, on the other hand, won't have any state or functionality; it's literally just a piece of UI. The best choice is to make it a functional component, because we can.

The rule for a class versus a functional component is essentially make a component functional wherever you can, unless you need state or methods.

Inside our src/ components folder, make a new file called Header.js. Then, we can create the skeleton of a functional component. Copy and paste the relevant div#Header from LoginContainer and add it as the return statement:

import React from 'react';

const Header = () => {
return (
<div id="Header">
<img src="/assets/icon.png" alt="logo" />
<h1>Chatastrophe</h1>
</div>
);
};

export default Header;

Now, back in our LoginContainer, we want to import our header, as illustrated:

import Header from './Header';

Then we can replace the div#Header with a simple <Header /> tag:

render() {
return (
<div id="LoginContainer" className="inner-container">
<Header />
<form onSubmit={this.handleSubmit}>
Another JSX gotcha--all JSX tags must be closed. You can’t just use <Header>.

That's it! That's all it takes to make a small, reusable component. Our LoginContainer now looks cleaner, and we’ve saved ourselves some typing down the road.

Our login form looks fantastic, but there's a problem. As you demo it for the team at Chatastrophe headquarters (the team having somehow swelled to twenty, despite you being the only developer), an intern raises her hand--"How does it actually, you know, work?"

主站蜘蛛池模板: 祁连县| 赤城县| 无锡市| 通州区| 朔州市| 灵璧县| 防城港市| 夏河县| 富平县| 永福县| 咸丰县| 治县。| 呼和浩特市| 绍兴市| 讷河市| 喀喇沁旗| 通榆县| 息烽县| 秦皇岛市| 阿拉善右旗| 库车县| 攀枝花市| 永德县| 清新县| 金川县| 彭州市| 清镇市| 凉城县| 都兰县| 九寨沟县| 阳山县| 香河县| 浦东新区| 攀枝花市| 蓝田县| 三都| 鄂伦春自治旗| 洛隆县| 哈巴河县| 寿光市| 汝州市|