为了账号安全,请及时绑定邮箱和手机立即绑定

类/功能组件,方法

类/功能组件,方法

蛊毒传说 2022-09-29 17:45:04
我对 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}             ]         })     }
查看完整描述

1 回答

?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

我有几个问题 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#autobinding


https://babeljs.io/docs/en/babel-plugin-transform-class-properties/


查看完整回答
反对 回复 2022-09-29
  • 1 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号