React 编程规范
发布时间:2020-12-15 04:43:19 所属栏目:百科 来源:网络整理
导读:React 编程规范 基本规则 命名 声明 对齐 引号 空格 属性 括号 标签 方法 顺序 基本规则 每个文件只包含一个 React 组件 使用 JSX 语法 除非是从一个非 JSX 文件中初始化 app,否则不要使用 React.createElement Class vs React.createClass 除非有更好的理
React 编程规范
基本规则
Class vs React.createClass
// bad
const Listing = React.createClass({
render() {
return <div />;
}
});
// good
class Listing extends React.Component {
render() {
return <div />;
}
}
命名
// bad
const reservationCard = require('./ReservationCard');
// good
const ReservationCard = require('./ReservationCard');
// bad
const ReservationItem = <ReservationCard />;
// good
const reservationItem = <ReservationCard />;
// bad
const Footer = require('./Footer/Footer.jsx')
// bad
const Footer = require('./Footer/index.jsx')
// good
const Footer = require('./Footer')
声明
// bad
export default React.createClass({
displayName: 'ReservationCard',// stuff goes here
});
// good
export default class ReservationCard extends React.Component {
}
对齐
// bad
<Foo superLongParam="bar" anotherSuperLongParam="baz" />
// good
<Foo superLongParam="bar" anotherSuperLongParam="baz" />
// if props fit in one line then keep it on the same line
<Foo bar="bar" />
// children get indented normally
<Foo superLongParam="bar" anotherSuperLongParam="baz" >
<Spazz />
</Foo>
引号
eslint rules: jsx-quotes // bad <Foo bar='bar' /> // good <Foo bar="bar" /> // bad <Foo style={{ left: "20px" }} /> // good <Foo style={{ left: '20px' }} />
空格
// bad
<Foo/>
// very bad
<Foo />
// bad
<Foo
/>
// good
<Foo />
属性
// bad
<Foo UserName="hello" phone_number={12345678} />
// good
<Foo userName="hello" phoneNumber={12345678} />
括号
/// bad
render() {
return <MyComponent className="long body" foo="bar">
<MyChild />
</MyComponent>;
}
// good
render() {
return (
<MyComponent className="long body" foo="bar">
<MyChild />
</MyComponent>
);
}
// good,when single line
render() {
const body = <div>hello</div>;
return <MyComponent>{body}</MyComponent>;
}
标签
// bad
<Foo className="stuff"></Foo>
// good
<Foo className="stuff" />
// bad
<Foo
bar="bar"
baz="baz" />
// good
<Foo
bar="bar"
baz="baz"
/>
方法
// bad
React.createClass({
_onClickSubmit() {
// do stuff
}
// other stuff
});
// good
class extends React.Component {
onClickSubmit() {
// do stuff
}
// other stuff
});
顺序
import React,{ PropTypes } from 'react';
const propTypes = {
id: PropTypes.number.isRequired,url: PropTypes.string.isRequired,text: PropTypes.string,};
const defaultProps = {
text: 'Hello World',};
class Link extends React.Component {
static methodsAreOk() {
return true;
}
render() {
return <a href={this.props.url} data-id={this.props.id}>{this.props.text}</a>
}
}
Link.propTypes = propTypes;
Link.defaultProps = defaultProps;
export default Link;
eslint rules: react/sort-comp (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |