我对ReactJ非常陌生,我正在努力了解更多的细节。
在Class组件中,我知道可以声明一个处理程序方法来更改状态,这是两种方法
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)如何反应知道classChangeState2是一种没有“函数”的方法?
2)我知道可以将newName作为上述所有方法中的参数传递,但必须在所有方法的呈现中绑定"THIS“。例如methodName.bind(这个,"newNamehere")
这是为什么?即使对于最初不需要绑定的函数组件,当我想将"newName“作为参数添加时,现在也必须绑定。有人能解释一下吗?
classChangeState=(newName)=>{
this.setState({
Person:[
{firstName:newName, secondName:55}
]
})
}发布于 2020-06-12 05:12:43
我有几个问题: 1)如何反应知道classChangeState2是一种没有“函数”的方法?
这与反应无关,但与ES6有关。类是语法糖,它们只是特殊的功能。作为一个方法,你所看到的只是分配给一个方法名称的函数的一个简短的手。所以当你写这个:
class fooClass {
bar(...) {}
}fooClass实际上是一个函数,其中用于bar的方法被写到fooClass.prototype中。另外,你也想看看,
从ECMAScript 2015开始,介绍了用于对象初始化器的方法定义的较短语法。它是分配给方法名称的函数的缩写。
const obj = {
foo() {
return 'bar';
}
};
console.log(obj.foo());谈到问题的第二部分,
2)我知道可以将newName作为上述所有方法中的参数传递,但必须在所有方法的呈现中绑定"THIS“。例如methodName.bind(这个,"newNamehere")
这个语法是实验班属性,您可以使用它而不是构造函数中的bind。请注意,此语法可能会更改。
阅读更多https://reactjs.org/docs/react-without-es6.html#autobinding
https://babeljs.io/docs/en/babel-plugin-transform-class-properties/
https://stackoverflow.com/questions/62336398
复制相似问题