jsx

react jsx

react short

Posted by gankai on February 27, 2019

1.使用JSX 简写

使用 JSX 来传递布尔变量。 假设您想控制“Navbar”组件的标题可见性。

bad

return (
  <Navbar showTitle={true} />
);

good

return(
  <Navbar showTitle />  
)

2.使用三元运算符

假设您希望根据角色显示特定用户的详细信息

bad

const { role } = user;

if(role === ADMIN) {
  return <AdminUser />
}else{
  return <NormalUser />
} 

good

const { role } = user;

return role === ADMIN ? <AdminUser /> : <NormalUser />

3.利用对象字面

对象文字可以帮助我们的代码更具可读性。假设您想根据角色显示三种类型的用户。你不能使用三元制,因为选项数大于两个。

bad

const {role} = user

switch(role){
  case ADMIN:
    return <AdminUser />
  case EMPLOYEE:
    return <EmployeeUser />
  case USER:
    return <NormalUser />
}

good

const {role} = user

const components = {
  ADMIN: AdminUser,
  EMPLOYEE: EmployeeUser,
  USER: NormalUser
};

const Component = components[role];

return <Componenent />;

4.使用碎片

Always use Fragment over **Div. It keeps the code clean and is also beneficial for performance because one less node is created in the virtual DOM

bad

return (
  <div>
     <Component1 />
     <Component2 />
     <Component3 />
  </div>  
)

good

return (
  <>
     <Component1 />
     <Component2 />
     <Component3 />
  </>  
)

5.不要定义渲染内部的函数

不要在渲染内部定义函数。尽量将内部逻辑渲染保持在绝对最小值。

bad

return (
    <button onClick={() => dispatch(ACTION_TO_SEND_DATA)}>    // NOTICE HERE
      This is a ### bad example 
    </button>  
)

good

const submitData = () => dispatch(ACTION_TO_SEND_DATA)

return (
  <button onClick={submitData}>  
    This is a ### good example 
  </button>  
)

6.使用备忘录

React.PureComponent and Memo can significantly improve the performance of your application. They help us to avoid unnecessary rendering.

bad

import React, { useState } from "react";

export const TestMemo = () => {
  const [userName, setUserName] = useState("faisal");
  const [count, setCount] = useState(0);
  
  const increment = () => setCount((count) => count + 1);
  
  return (
    <>
      <ChildrenComponent userName={userName} />
      <button onClick={increment}> Increment </button>
    </>
  );
};

const ChildrenComponent =({ userName }) => {
  console.log("rendered", userName);
  return <div> {userName} </div>;
};

Although the child component should render only once because the value of count has nothing to do with the ChildComponent . But, it renders each time you click on the button.

good

import React ,{useState} from "react";

const ChildrenComponent = React.memo(({userName}) => {
    console.log('rendered')
    return <div> {userName}</div>
})

7.将CSS放入JavaScript中

在编写 React 应用程序时,尽量避免原始 JavaScript,因为组织 CSS 比组织 JS 困难得多。

bad

// CSS FILE

.body {
  height: 10px;
}

//JSX

return <div className='body'>
   
</div>

good

const bodyStyle = {
  height: "10px"
}

return <div style={bodyStyle}>

</div>

8.使用对象析构

使用对象析构对您有利。假设您需要显示用户的详细信息。

bad

return (
  <>
    <div> {user.name} </div>
    <div> {user.age} </div>
    <div> {user.profession} </div>
  </>  
)

good

const { name, age, profession } = user;

return (
  <>
    <div> {name} </div>
    <div> {age} </div>
    <div> {profession} </div>
  </>  
)

9.弦道具不需要卷花括号

将字符串道具传递给子组件时。

bad

return(
  <Navbar title={"My Special App"} />
)

good

return(
  <Navbar title="My Special App" />  
)

10。从JSX中删除JS代码

如果任何JS代码没有用于渲染或用户界面功能,则将任何JS代码从JSX中移出。

bad

return (
  <ul>
    {posts.map((post) => (
      <li onClick={event => {
        console.log(event.target, 'clicked!'); // <- THIS IS ### bad
        }} key={post.id}>{post.title}
      </li>
    ))}
  </ul>
);

good

const onClickHandler = (event) => {
   console.log(event.target, 'clicked!'); 
}

return (
  <ul>
    {posts.map((post) => (
      <li onClick={onClickHandler} key={post.id}> {post.title} </li>
    ))}
  </ul>
);

11.使用模板文字

使用模板文字来构建大字符串。避免使用字符串串联。它很好,也很干净。

bad

const userDetails = user.name + "'s profession is" + user.proffession

return (
  <div> {userDetails} </div>  
)

good

const userDetails = `${user.name}'s profession is ${user.proffession}`

return (
  <div> {userDetails} </div>  
)

const userDetails = ${user.name}'s profession is ${user.proffession}

return (

{userDetails}

)




# 12.有序进口

总是尝试按一定顺序导入东西。它提高了代码的可读性。


### bad

import React from ‘react’; import ErrorImg from ‘../../assets/images/error.png’; import styled from ‘styled-components/native’; import colors from ‘../../styles/colors’; import { PropTypes } from ‘prop-types’;


### good
经验法则是这样保持导入顺序:

-   内置
-   外部
-   内部

所以上面的例子变成了:

import React from ‘react’;

import { PropTypes } from ‘prop-types’; import styled from ‘styled-components/native’;

import ErrorImg from ‘../../assets/images/error.png’; import colors from ‘../../styles/colors’;



# 13.使用隐式退货

Use the JavaScript feature of implicit `return` to write beautiful code. Let’s say your function does a simple calculation and returns the result.

### bad 

const add = (a, b)=>{ return a + b; }


### good

const add = (a, b)=> a + b;

# 14.组件命名

始终使用PascalCase作为组件,为实例使用骆驼Case。
### bad

import reservationCard from ‘./ReservationCard’;

const ReservationItem = ;

### good

import ReservationCard from ‘./ReservationCard’;

const reservationItem = ;


# 15.保留道具名称

不要使用DOM组件道具名称在组件之间传递道具,因为其他人可能不会期望这些名称。

### bad

### good

# 16.引语

JSX属性使用双引号,所有其他JS使用单引号。

### bad

<Foo style= />

### good

<Foo style= />


# 17.道具命名

如果道具值是React组件,则始终使用骆驼壳作为道具名称或PascalCase。

### bad

<Component UserName=”hello” phone_number={12345678} />

### good

<MyComponent userName=”hello” phoneNumber={12345678} Component={SomeComponent} />


# 18.括号中的JSX

如果您的组件跨越多行,请始终将其包裹在括号中.

### bad

return ;


### good

return ( );


# 19.自闭标签

如果您的组件没有任何子组件,请使用自闭标签。它提高了可读性。

### bad

### good



# 20.方法名称中的下划线

在任何内部React方法中不要使用下划线

### bad

const _onClickHandler = () => { // do stuff }


### good

const onClickHandler = () => { // do stuff } ```