未定义ReactJS Uncaught ReferenceError函数

时间:2016-01-12 07:59:55

标签: reactjs ecmascript-6

我正在尝试使用ES6语法在React中实现自定义验证。

import React, { Component } from 'react';

export default class Board extends Component {

    constructor(props) {
    super(props);
  }

  static propTypes = { count: validate };

  validate(props, propName, componentName){  
    if (props[propName]) {
      let value = props[propName];
      if (typeof value === 'number') {
          if (value > 100) {
            return new Error("Value cannot be more than 100");
          }
      }
      else{
        return new Error('Count should be a number')
      }
    }
  };

  render() {
    return (
      <div className="board">{this.props.count}</div>
    );
  }
}

当我运行此代码时,出现错误“Uncaught ReferenceError:validate not defined”。如果有人能帮我解决这个问题,我将不胜感激。

2 个答案:

答案 0 :(得分:2)

您无法从静态属性访问实例属性,因此最简单的解决方案是将UTL_I18N.RAW_TO_CHAR ('F48FBFBF', 'AL32UTF8')设置为静态。

validate

static propTypes = { count: Board.validate } static validate(props, propName, componentName) { // ... } 似乎也有用,但我不喜欢静态和使用this.validate的组合。

答案 1 :(得分:2)

import React, { Component } from 'react';

export default class Board extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div className="board">{this.props.count}</div>
        );
    }
}

const validate = (props, propName, componentName) => {  
    if (props[propName]) {
        let value = props[propName];
        if (typeof value === 'number') {
            if (value > 100) {
                return new Error("Value cannot be more than 100");
            }
        }
        else{
            return new Error('Count should be a number')
        }
    }
};

Board.propTypes = {
    count: validate
}

或更简单......

import React, { Component } from 'react';

export default class Board extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div className="board">{this.props.count}</div>
        );
    }
}

Board.propTypes = {
  count: (props, propName, componentName) => {  
    if (props[propName]) {
        let value = props[propName];
        if (typeof value === 'number') {
            if (value > 100) {
                return new Error("Value cannot be more than 100");
            }
        }
        else{
            return new Error('Count should be a number')
        }
    }
  }
}