文章目录
github
更多前端资源和知识整理:https://github.com/ChenMingK/WebKnowledges-Notes
1. 基本规范
- 每个文件只写一个模块
- 但是多个无状态模块可以放在单个文件中. eslint: react/no-multi-comp
- 推荐使用 JSX 语法
- 不要使用
React.createElement
,除非从一个非 JSX 的文件中初始化你的 app
2. 创建模块
- 如果你的模块有内部状态或者是 refs, 推荐使用 class extends React.Component 而不是 React.createClass,也就是说推荐使用 ES6 语法创建 component
// bad
const Listing = React.createClass({
// ...
render() {
return <div>{
this.state.hello}</div>
}
});
// good
class Listing extends React.Component {
// ...
render() {
return <div>{
this.state.hello}</div>
}
}
// bad (relying on function name inference is discouraged)
const Listing = ({
hello }) => (
<div>{
hello}</div>
);
// good
function Listing({
hello }) {
return <div>{
hello}</div>
}
3. 命名
- 扩展名: 使用 .jsx 作为 React 组件的扩展名
- 文件名: 使用帕斯卡命名法命名文件,譬如 ReservationCard.jsx
- 引用命名: 使用帕斯卡命名法命名组件和 camelCase 命名实例
// bad
const reservationCard = require('./ReservationCard')
// good
const ReservationCard = require('./ReservationCard')
- 模块命名: 模块使用当前文件名一样的名称. 比如 ReservationCard.jsx 应该包含名为 ReservationCard 的模块. 但是,如果整个文件夹是一个模块,使用 index.js 作为入口文件,然后直接使用 index.js 或者文件夹名作为模块的名称
// bad
import Footer from './Footer/Footer';
// bad
import Footer from './Footer/index'