导航
React.createElement如果使用 JavaScript,则文件扩展名为 .js;如果使用 TypeScript,则文件扩展名为 .tsx
如果是组件文件,则使用 PascalCase,如 MyComponent.js
如果组件是一个目录,则组件主入口命名为 index,如 index.js
React 组件使用 PascalCase,组件实例使用 CamelCase
// bad
import reservationCard from './ReservationCard';
// good
import ReservationCard from './ReservationCard';
// bad
const ReservationItem = <ReservationCard />;
// good
const reservationItem = <ReservationCard />;
使用文件名作为组件名字,例如, ReservationCard.js 应该包含名为 ReservationCard 的引用,然而对于文件夹中的根组件, 使用 index.js 作为文件名,使用文件夹的名字作为组件的名字
// bad
import Footer from './Footer/Footer';
// bad
import Footer from './Footer/index';
// good
import Footer from './Footer';
React DOM 使用小驼峰式命名法来定义属性的名称,而不使用 HTML 属性名称的命名约定,例如
<div onClick={this.handler} />
只允许使用 Class Component 和 Functional Component 两种形态来书写组件,建议尽量使用函数式组件配合 Hooks 来进行开发
// bad
<Foo
UserName='hello'
phone_number={12345678}
/>
// good
<Foo
userName='hello'
phoneNumber={12345678}
/>
// bad
<Foo
hidden={true}
/>
// good
<Foo
hidden
/>
// good
<Foo hidden />
避免使用字符串引用,请使用回调函数作为引用
// bad
<Foo
ref='myRef'
/>
// good
<Foo
ref={ref => { this.myRef = ref }}
/>
当 JSX 标签超过一行时使用圆括号包裹
// 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>
}
function ItemList (props) {
return (
<ul>
{props.items.map((item, index) => (
<Item
key={item.key}
onClick={() => doSomethingWith(item.name, index)}
/>
))}
</ul>
)
}
// bad
class extends React.Component {
_onClickSubmit () {
// do stuff
}
// other stuff
}
// good
class extends React.Component {
onClickSubmit () {
// do stuff
}
// other stuff
}
// bad
render () {
(<div />)
}
// good
render () {
return (<div />)
}
不要在循环,条件或嵌套函数中调用 Hook, 确保总是在你的 React 函数的最顶层调用他们
// bad
function a () {
const [count, setCount] = useState(0)
useEffect(function persistForm() {
localStorage.setItem('formData', accountName)
})
const x = function () {}
const [timer, setTimer] = useState(0)
// main logic
}
// bad
function a () {
const [count, setCount] = useState(0)
useEffect(function persistForm() {
localStorage.setItem('formData', accountName)
})
const [timer, setTimer] = useState(0)
const x = function () {}
// main logic
}