将propTypes和defaultProps作为静态道具放在React类中是否可以?

ffx*_*sam 35 class reactjs ecmascript-next

这是我现在已经做了很长时间的方式了:

export default class AttachmentCreator extends Component {
  render() {
    return <div>
      <RaisedButton primary label="Add Attachment" />
    </div>
  }
}

AttachmentCreator.propTypes = {
  id: PropTypes.string,
};
Run Code Online (Sandbox Code Playgroud)

但我看到有人这样做:

export default class AttachmentCreator extends Component {
  static propTypes = {
    id: PropTypes.string,
  };

  render() {
    return <div>
      <RaisedButton primary label="Add Attachment" />
    </div>
  }
}
Run Code Online (Sandbox Code Playgroud)

事实上,我已经看到人们在构造函数之外设置初始状态.这是好习惯吗?这一直困扰着我,但我记得在某个地方有人说将默认道具设置为静态不是一个好主意的讨论 - 我只是不记得原因.

dan*_*del 38

事实上,它在性能方面完全相同.React.JS是一项相对较新的技术,因此尚不清楚什么是好的做法或不做.如果您想信任某人,请查看AirBNB的风格指南:

https://github.com/airbnb/javascript/tree/master/react#ordering

import React, { PropTypes } from 'react';

const propTypes = {
  id: PropTypes.number.isRequired,
  url: PropTypes.string.isRequired,
  text: PropTypes.string,
};

const defaultProps = {
  text: 'Hello World',
};

class Link extends React.Component {
  static methodsAreOk() {
    return true;
  }

  render() {
    return <a href={this.props.url} data-id={this.props.id}>{this.props.text}</a>
  }
}

Link.propTypes = propTypes;
Link.defaultProps = defaultProps;

export default Link;
Run Code Online (Sandbox Code Playgroud)

他们使用propTypes对象文字声明一个const,保持该类非常干净,稍后将它们分配给静态属性.我个人喜欢这种方法:)


Qwe*_*rty 13

哦,是的,它完全与巴别塔合法

class DataLoader extends React.Component {
  static propTypes = {
    onFinishedLoading: PropTypes.func
  }

  static defaultProps = {
    onFinishedLoading: () => {}
  }
}
Run Code Online (Sandbox Code Playgroud)

......无论如何它都被转化为了这个.

class DataLoader extends React.Component {}

DataLoader.propTypes = {
  onFinishedLoading: PropTypes.func
};

DataLoader.defaultProps = {
  onFinishedLoading: () => {}
};
Run Code Online (Sandbox Code Playgroud)

静态字段在引擎盖下被转换为类属性. 看看Babel REPL.

此外,直接在类中分配状态或其他类字段会被转换为实例构造函数.


Phi*_*arg 11

es2015类目前不支持非函数属性.它是es2016的提案.第二种方法相当方便,但需要一个插件来支持语法(这是一个非常常见的babel插件).

另一方面,一个充满开源项目的手开始处理像TypeScript接口或ActionConstants这样的proptypes,并实际创建包含各种组件prop类型的单独文件夹/文件,然后导入到组件中.

总而言之,这两种语法都可以使用.但如果您只想严格使用ES2015,则规范中尚不支持后一种语法.