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

A beginner's guide to naming

Naming may sound trivial, but there are some standard practices in React that you should comply with. These practices may vary from project to project, but keep in mind that you should respect at least the ones that are mentioned here. In other cases, check your project's style guide and possibly your linter configuration.

One of the great React style guides comes from Airbnb and can be checked out at  https://github.com/airbnb/javascript/tree/master/react#naming.

A component name should start with an uppercase letter unless it's a HOC. Use the component name as the filename. The filename should be in UpperCamelCase (for more information on CamelCase, see https://en.wikipedia.org/wiki/Camel_case):

// bad
someSection.js
// good
SomeSection.js or SomeSection.jsx
// Current Airbnb style guide recommends .jsx extension though.

The following are rules on importing your component:

// bad
import App from './App/App';

// bad
import App from './App/index';

// good
import App from './App';

If it's HOC, start its name with a lowercase letter in lower CamelCase, for instance, makeExpandable.

Airbnb also suggests that you take care of the name of the inner component. We need to specify a displayName prop to do, as in the following:

// Excerpt from
// https://github.com/airbnb/javascript/tree/master/react#naming
// bad
export default function withFoo(WrappedComponent) { return function WithFoo(props) { return <WrappedComponent {...props} foo />; } } // good export default function withFoo(WrappedComponent) { function WithFoo(props) { return <WrappedComponent {...props} foo />; } const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component'; WithFoo.displayName = `withFoo(${wrappedComponentName})`; return WithFoo; }

This is a valid point as in some tools you may benefit from seeing the proper component names. Following this pattern is optional and up to the team to decide upon.

One can create a HOC that takes care of the  displayName  prop. Such a HOC can be reused on top of the HOCs we created in Chapter 1, React Component Patterns.

When defining new props, please avoid the common props that used to mean something else. An example may be the style prop we used to pass styles to our components.
Please check out the following links to check what props you should avoid using:

Don't get too scared. It will feel more natural sooner or later.

主站蜘蛛池模板: 平武县| 康定县| 平山县| 平昌县| 綦江县| 武定县| 白朗县| 重庆市| 千阳县| 合江县| 永州市| 汨罗市| 五大连池市| 泰州市| 屯留县| 金川县| 静宁县| 安陆市| 凤台县| 聂荣县| 石河子市| 荣昌县| 麻江县| 闽清县| 察隅县| 沛县| 周至县| 巴楚县| 巴彦淖尔市| 浏阳市| 疏勒县| 玛曲县| 萍乡市| 平果县| 古蔺县| 莆田市| 阿拉善盟| 黄浦区| 昆山市| 宁河县| 时尚|