整理一下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 This is the sample component
    } else {
      return Please reInit this component.
    }
  }
  
  //私有方法,名字要以_开头
  _privateMethod() {
  }
}
  
const styles = StyleSheet.create({
  xx: {
  }
});

你可能感兴趣的:(整理一下react-native开发规范)