欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
用更合理的方式书写React和JSX
 
基本规则
 
每个文件只包含一个React组件;
 
但是无状态, 或者 Pure 组件 允许一个文件包含多个组件.eslint: react/no-multi-comp.
 
始终使用 JSX 语法;
 
不要使用 React.createElement方法,除非初始化 app 的文件不是 JSX 格式.
 
Class vs React.createClass vs stateless
 
如果组件拥有内部的 state 或者 refs 的时,更推荐使用 class extends React.Component,除非你有一个非常好的理由要使用 mixin. eslint: react/prefer-es6-class
 
// 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>;
 
  }
 
}
 
如果没有组件没有内部 state 或者 refs,那么普通函数 (不要使用箭头函数) 比类的写法更好:
 
// bad
 
class Listing extends React.Component {
 
  render() {
 
    return <div>{this.props.hello}</div>;
 
  }
 
}
 
// bad (因为箭头函数没有“name”属性)
 
const Listing = ({ hello }) => (
 
  <div>{hello}</div>
 
);
 
// good
 
function Listing({ hello }) {
 
  return <div>{hello}</div>;
 
}
 
命名
 
扩展名:React 组件使用.jsx扩展名;
 
文件名:文件名使用帕斯卡命名. 例如: ReservationCard.jsx.
 
引用命名:React 组件使用帕斯卡命名,引用实例采用驼峰命名. eslint: react/jsx-pascal-case
 
// bad
 
import reservationCard from './ReservationCard';
 
// good
 
import ReservationCard from './ReservationCard';
 
// bad
 
const ReservationItem = <ReservationCard />;
 
// good
 
const reservationItem = <ReservationCard />;
 
组件命名:组件名称应该和文件名一致, 例如: ReservationCard.jsx 应该有一个ReservationCard的引用名称. 但是, 如果是在目录中的组件, 应该使用 index.jsx 作为文件名 并且使用文件夹名称作为组件名:
 
// bad
 
import Footer from './Footer/Footer';
 
// bad
 
import Footer from './Footer/index';
 
// good
 
import Footer from './Footer';
 
声明
 
不要使用——displayName——属性来命名组件,应该使用类的引用名称.
 
// bad
 
export default React.createClass({
 
  displayName: 'ReservationCard',
 
  // stuff goes here
 
});
 
// good
 
export default class ReservationCard extends React.Component {
 
}

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h63647.shtml