反应组成成分的类型

时间:2017-01-17 17:48:29

标签: reactjs react-proptypes

我正在使用组合模式进行反应。所以,例如,我有这个简单的组件:

  let amountExpr = NSExpression(forKeyPath: "amount")
    let sumExpr = NSExpression(forFunction: "sum:", arguments: [amountExpr])
    let sumDescr = NSExpressionDescription()
    sumDescr.expression = sumExpr
    sumDescr.name = "sumOfAmount"
    sumDescr.expressionResultType = .doubleAttributeType

    let dateExpr = NSExpression(forKeyPath: "date")
    let dateDescr = NSExpressionDescription()
    dateDescr.expression = dateExpr
    dateDescr.name = "date"
    dateDescr.expressionResultType = .dateAttributeType

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Transaction")
    request.sortDescriptors = Transaction.defaultSortDescriptors
    request.propertiesToFetch = [dateDescr, sumDescr]
    request.propertiesToGroupBy = [dateDescr]
    request.resultType = .dictionaryResultType
    request.returnsObjectsAsFaults = false
    request.predicate = Transaction.rangeOfDatesPredicate(dateRange: Date.week())
    let results = try! context.fetch(request) as! [NSDictionary]

现在,我有了这个增强的组件:

class Simple extends React.Component {
  render() {
    return <div>{this.props.text}</div>;
  }
}

Simple.propTypes = {
  text: React.PropTypes.string.isRequired
};

现在,我如何指定增强组件的proptypes?我能做到这一点:

class Enhanced extends React.Component {
  render() {
    return (
      <div>
        <div>Hi, I'm the enhanced version</div>
        <Simple {...this.props} />
      </div>
    );
  }
}

但这并不好,因为我必须列出Enhanced.propTypes = { text: React.PropTypes.string.isRequired }; 组件的所有道具,每当我更改这些道具时,我都必须在Simple中更改它们

1 个答案:

答案 0 :(得分:3)

propTypes只是普通的JS对象。你可以随意编写它们:

// Simple.js
export const simplePropTypes = {
  text: React.PropTypes.string.isRequired
}

Simple.propTypes = simplePropTypes

// Enhanced.js
import Simple, { simplePropTypes } from './Simple'

Enhanced.propTypes = {
  somethingElse: React.PropTypes.number,
  ...simplePropTypes
}

<强>更新

应该能够直接使用组件定义的propTypes

Enhanced.propTypes = {
  somethingElse: React.PropTypes.number,
  ...Simple.propTypes
}