const关键字和方法声明出现问题

时间:2019-02-04 15:51:24

标签: javascript reactjs

我正在尝试新的React Hooks API,并且想知道为什么函数组件内部的此方法声明不起作用:

const Foo = (props) => {

    const [..., ...] = useState(...);
    ...
    onChange = (e) => { ... }

我在下面收到此错误

'onChange' is not defined  no-undef

enter image description here

但是当我添加const关键字时,它会起作用。

const onChange = (e) => { ... }

1 个答案:

答案 0 :(得分:4)

语法

const Foo = (props) => {/* */} 

声明一个普通的javascript函数并将其分配给变量Foo。这不是要与类混淆。您不能像使用类属性语法的类那样在其上声明“属性”。在课程中,您可以做到这一点:

class MyComp extends Component {
    onChange = e => {/* ... */}  // this declares `onChange` as a property

    render() {
        // you can use this.onChange here

        return (
            <input onChange={this.onChange} ... />
        )
    }
}

但是对于功能组件,这是无效的:

const MyComp = () => {
    // this is the body of the function

    onChange = e => {/* ... */};   // MyComp is not a class so you can't just declare proteries on it.
}

但这是正确的语法:

const MyComp = () => {
    const onChange = e => {/* ... */}; 
}

但是它可能没有按照您的想法做。它只是在onChange函数内部创建一个局部变量MyComp。因此,错误onChange is not defined。您将一个函数分配给在使用前未声明的变量onChange。首先需要使用关键字constletvar对其进行声明。

即使您没有声明变量,代码也可能仍然有效,因为解释器将其默默地视为全局变量声明,这可能不是您想要的。

相关问题