整理一下react-native开发规范

代码组织结构
SomeComponent // 首字母大写,文件夹
  index.js // 入口,为了引用方便,里面只需要import default from ‘./SomeCompoent'
  SomeComponent.js // 首字母大写,具体实现,为了查找文件方便,都叫index.js也是灾难
  SomeComponent.test.js // 首字母大写,使用jest框架做单元测试

对于展示组件,要求一定要在文件的最开始定义PropTypes,写上组件所支持的props,并简单说明每个prop是什么含义。

代码规范
  • propTypes统一写在文件最开始,把组件支持的所有属性以及类型列出来,给出注释
  • constructor里把组件的state全部初始化
  • 组件内的代码顺序为:

  1. propTypes定义
  2. static方法
  3. constructor
  4. public方法(准备公开给外部调用的方法)
  5. 组件生命周期方法
  6. render方法
  7. 私有方法(必须以_开头)

示例:

//LearnReactNative.js
  
//文件最开始把propTypes提出来,方便阅读
const propTypes = {
  // 属性描述
  sampleProp: PropTypes.bool.isRequired
}
  
class LearnReactNative extends Component {
  //propTypes定义
  static propTypes = propTypes;
  
  //如果需要定义static方法,放在这里
  static getSampleProp(): boolean {
    return true;
  }   
  
  //constructor方法,里面要初始化state
  constructor(props) {
    super(props);
    this.state = {
      sampleState: this.props.sampleProp
    }
  }
  
  //准备公开给外部调用的方法
  publicMethod() {
  }
   
  //生命周期方法(按需添加)
  componentWillMount() {}
  componentDidMount() {}
  componentWillReceiveProps() {}
  shouldComponentUpdate() {}
  componentWillUpdate() {}
  componentDidUpdate() {}
  
  //render方法
  render() {
    if(this.state.sampleState) {
      return <Text>This is the sample component</Text>
    } else {
      return <Text>Please reInit this component.</Text>
    }
  }
  
  //私有方法,名字要以_开头
  _privateMethod() {
  }
}
  
const styles = StyleSheet.create({
  xx: {
  }
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • GUIDS 第一章 为什么使用React? React 一个提供了用户接口的JavaScript库。 诞生于Fac...
    jplyue阅读 3,611评论 1 11
  • 深入JSX date:20170412笔记原文其实JSX是React.createElement(componen...
    gaoer1938阅读 8,112评论 2 35
  • React-Native开发规范 标签(空格分隔): React-Native JavaScript 一、编程规约...
    德山_阅读 1,598评论 1 0
  • 幸福就像是盒子里的巧克力糖 只有自己努力踮起脚尖 才能得到
    加一11阅读 206评论 0 2
  • 站在窗前凝望着雨水倾泄而下,听着雨点无情的敲打玻璃窗的声音,任泪水悄无声息的流…… 不知多少次细数着日历...
    从容sunshine阅读 166评论 0 0