从getDefaultProps()访问组件方法时,为什么访问组件方法未定义?

问题描述 投票:0回答:1

我有一个自定义typeahead组件,我试图修改,我想传递一个自定义onBlur方法从父到子。

如果没有传递getDefaultProps,我定义了onBlur

  getDefaultProps: function () {
    console.log(this.handleBlur) // undefined
    return {
      onChange: function () {},
      onBlur: this.handleBlur
    }
  }

handleBlur是我想要访问的组件内部的方法。我如何访问组件内部的方法?

reactjs
1个回答
0
投票

内部React在实例化Class之前获取默认道具。这意味着getDefaultProps函数是类的静态方法。如果使用createReactClass创建反应组件,那么它就不是一个静态方法。

在javascript中有不同的创建静态函数或变量的方法:

// 1. Old JS:
function Foo() {}
Foo.staticFunction = function(){}
var foo = new Foo();
// typeof Foo.staticFunction === 'function'
// typeof foo.staticFunction === 'undefined'

// 2. ES6:
class Foo {
    static myFunction = () => { ... }
}

当您使用ES6时,您可以编写类似的内容

// add the onBlur function outside of the class scope
const handleBlur = event => { /*  your fallback blur handler */ }

class MyComponent extends Component {
    static defaultProps = {
        handleChange() {},
        handleBlur,
    };
}

另一种方法是在构造函数中设置blurHandler:

class MyComponent extends Component {
    constructor(props, context) {
        super(props, context)

        if (!this.props.blurHandler) {
            this.blurHandler = this.defaultBlurHandler
        }
    }
    defaultBlurHandler = () => { /* do your stuff here */ }
}
© www.soinside.com 2019 - 2024. All rights reserved.