类/功能组件,方法

我对 ReactJs 很陌生,我正试图了解更多细节。


在类组件中,我知道这两种方式可以声明处理程序方法来更改状态。


 classChangeState=()=>{

         this.setState({

             Person:[

                 {firstName:"test", secondName:55}

             ]

         })

     }


classChangeState2(){

    console.log("Inside Change state click")

    this.setState({

         Person:[

             {firstName:"test", secondName:55}

         ]

     })enter code here

 //classChangeState2 require me to bind "this" inside render method

在功能组件中,以下两种方式我都可以做到


    function changeStateClick(){

            changeState({

             Person:[

                {firstName: "Just aasefaesfstring property", secondName: 32}

            ]

        })

        }


    const changeStateClick2 =()=> changeState({

             Person:[

                {firstName: "Just a[[[string property", secondName: 32}

            ]

        })

我有几个问题 1) React 如何知道类ChangeState2 是一个没有“函数”的方法?


2)我知道我可以在上述所有方法中传入newName作为参数,但我必须在所有方法的渲染中绑定“THIS”。例如,对于方法名称.bind(this,“newNamehere”)


这是为什么呢?即使对于功能组件,当我想要添加“newName”作为参数时,最初我不需要绑定,我现在也必须绑定。有人可以解释一下吗?


classChangeState=(newName)=>{

         this.setState({

             Person:[

                 {firstName:newName, secondName:55}

             ]

         })

     }


蛊毒传说
浏览 156回答 1
1回答

汪汪一只猫

我有几个问题 1) React 如何知道类ChangeState2 是一个没有“函数”的方法?它与 React 无关,但与 ES6 无关。类是语法糖,它们只是特殊函数。你所看到的方法只是分配给方法名称的函数的简写。所以当你写这个的时候:   class fooClass {    bar(...) {}    }fooClass实际上是一个函数,其中的方法例如被写入 。另外,你想看看,barfooClass.prototype从 ECMAScript 2015 开始,引入了对象初始值设定项上的方法定义的简短语法。它是分配给方法名称的函数的简写。 const obj = {  foo() {    return 'bar';  }};console.log(obj.foo());您可以了解有关 MDN 类和函数定义 MDN 的更多信息来到问题的第二部分,2)我知道我可以在上述所有方法中传入newName作为参数,但我必须在所有方法的渲染中绑定“THIS”。例如,对于方法名称.bind(this,“newNamehere”)此语法是实验性类属性,您可以使用它而不是在构造函数中使用该方法。请注意,此语法可能会更改。bind阅读更多 https://reactjs.org/docs/react-without-es6.html#autobindinghttps://babeljs.io/docs/en/babel-plugin-transform-class-properties/
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript