码迷,mamicode.com
首页 > 其他好文 > 详细

react编码规范

时间:2018-02-18 17:43:24      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:静态   led   contex   文件   驼峰   type   数组   单行   调用   

1、每个文件只写一个组件,但是多个无状态组件可以放在单个文件中

2、有内部状态,方法或要对外暴露ref的组件,用类式组件

3、无内部状态,方法或无需对外暴露ref的组件,用函数式组件

4、有内部状态,方法或要对外暴露ref的组件,使用es7类静态属性

class Button extends Component {
static propTypes = {
size: React.PropTypes.oneOf([‘large‘,‘normal‘,‘small‘]),
shape: React.PropTypes.oneOf([‘default‘,‘primary‘,‘ghost‘]),
disabled: React.PropTypes.bool
};

static defaultProps = {
size: ‘normal‘,
shape: ‘default‘,
disabled: false
};


}

5、无内部状态,方法或无需对外暴露ref的组件,使用类静态属性写法

const HelloMessage = ({name}) => {
return <div>Hello {name} </div>;
}
HelloMessage.propTypes = {
name: React.PropTypes.string
};

HelloMessage.defaultProps = {
name: ‘vic‘
}

6、PropTypes必须

7、为了调试方便,在组件最上方写displayName

class Some extends Component {
static displayName = ‘Some‘;
}

8、react组件文件用jsx,用大驼峰命名jsx文件

9、jsx的属性值总是使用双引号,其他用单引号。

<Foo bar="bar"/>

<Foo style={{ left: ‘20px‘ }} />

10、在自闭合组件前加一个空格<Foo />

11、不要在jsx{}里两边加空格<Foo bar={baz} />

12、不要在等号两边加空格

<Foo bar={baz} />

13、jsx属性名总是使用驼峰式风格

14、如果属性值为true,可以直接省略。

<Foo hidden />

13、遍历数组,输出相同的React组件,属性key必须

[<Hello key="first" />, <Hello key="second" />, <Hello key="third" />]

14、总是在Refs里使用回调函数

<Foo

ref={ref => { this.myRef = ref; }}

/>

15、将多行的jsx标签写在()里,单行可忽略()

在render方法中

return <div>dddd</div>

return (

<MyCom className="lon">dddd</MyCom>

)

16、render方法必须有值返回

18、没有子元素,自闭合

<MyCom className="lon" />

17、按照以下顺序排序方法

1、static methods and properties
2、lifecycle methods :displayName, propTypes, contextTypes , childContextTypes, mixins, statics, defaultProps, constructor, getDefaultProps, getInitialState,  state, getChildContext, componentWillMount, componentDidMount, componentWillReceiveProps, shouldComonentUpdate, componentWillUpdate, componentDidUpdate, componentWillUnmount

3、custom methods
4、render method

18、不要在componentDidMount或componentDidUpdate中调用setState,除非 在绑定回调函数中设置State。

class Hello extends Component {
    componentDidMount() {
        this.onMount(newName =>k {
            this.setState({
                name: newName
            });
        });
    }
    render() {
        return <div>Hello {this.state.name}</div>;
    }
}

19、不要给函数添加下划线前缀

下划线前缀在某些语言中通常表示私有变量或者函数,但是js中没有原生支持所谓的私有变量,所有的变量函数都是共有的。

 

react编码规范

标签:静态   led   contex   文件   驼峰   type   数组   单行   调用   

原文地址:https://www.cnblogs.com/camille666/p/react_coding_rules.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!