【发布时间】:2020-06-12 02:07:56
【问题描述】:
我对 ReactJs 很陌生,我正在尝试了解更多细节。
在 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)React 怎么知道 classChangeState2 是一个没有“函数”的方法?
2) 我知道我可以在上述所有方法中传入一个 newName 作为参数,但我必须在所有方法的渲染中绑定“THIS”。例如 methodName.bind(this,"newNamehere")
这是为什么?即使对于最初我想添加“newName”作为参数时不需要绑定的功能组件,我现在也必须绑定。有人可以解释一下吗?
classChangeState=(newName)=>{
this.setState({
Person:[
{firstName:newName, secondName:55}
]
})
}
【问题讨论】:
-
你真的很想花点时间浏览一下reactjs.org/tutorial/tutorial.html——它写得很好,它实际上涵盖了所有的基础知识,之后你在 React 上的表现会无限好。打开代码编辑器,实际运行示例,学习 React。是时候好好度过了。
-
是的,我确实经历过,但我觉得在我仍然迷失的某些部分不够详细,我了解了道具和组件如何工作的整体流程,但我觉得有时我认为太多了,它会使我的大脑复杂化。关于我的问题,我也浏览了文档,但我之间仍然存在漏洞。无论如何谢谢!
-
另一个是你还想要一个关于现代 JS 的好教程(不是仍然教 1998 年无意义 JS 的数百万个教程中的任何一个),以解释现代构造(如类、箭头函数等)是如何实现的。工作,何时使用它们,以及为什么(例如:如果您不需要保留
this的含义,则使用箭头函数实际上没有任何好处)。
标签: javascript reactjs class react-functional-component