【问题标题】:ReactJS Uncaught ReferenceError function is not definedReactJS Uncaught ReferenceError 函数未定义
【发布时间】:2016-01-12 07:59:54
【问题描述】:

我正在尝试使用 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>
    );
  }
}

当我运行此代码时,我收到一个错误“未捕获的 ReferenceError:验证未定义”。如果有人能帮我解决这个问题,我将不胜感激。

【问题讨论】:

  • propTypesstatic,因此不应访问 instance 方法。要么将validate 设为静态,要么将propTypes 设为实例变量

标签: reactjs ecmascript-6


【解决方案1】:
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')
        }
    }
  }
}

【讨论】:

    【解决方案2】:

    您无法从静态属性访问实例属性,因此最简单的解决方案是将validate 也设为静态。

    static propTypes = { count: Board.validate }
    static validate(props, propName, componentName) {  
      // ...
    }
    

    this.validate 似乎也可以,但我不喜欢静态和使用 this 的组合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      相关资源
      最近更新 更多