javascript - React 用法中的构造函数/超级/绑定它们指定了什么?
问题描述
我查找了 General JS 中constructor
的super
和bind
。
示例代码。
import React from 'react';
class Example extends React.Component {
constructor(props){
super(props);
this.state = { mood: confused }
this.doNothing = this.doNothing.bind(this);
}
doNothing(){} //I really do nothing
render(){
<button onClick={this.doNothing}>I do nothing xD</button>
}
}
这是我现在所理解的
State
是一个对象,为了在我需要使用的类中创建一个对象constructor
子类
constructor
将覆盖父类constructor
,我不知道里面有什么,React.Component
但我相信它很重要。我认为在 React Document 中也说过:类组件应始终使用 props 调用基本构造函数。
super
会帮我做继承,super
是替代父母的constructor
。如果我需要使用this
inconstructor
我需要编写super
并走得更远,我需要传递一个参数 dosuper(props)
才能使用this.props
bind
将创建一个与对象绑定良好的新函数,确保在调用该函数时,它将直接指向正确的对象,因为由于某种原因,如果我不绑定它,我的按钮会像<button onClick={undefined.doNothing}>
,因为一些类规则:/(可选参数也可以帮助我设置有趣的前置参数,但这不是让我烦恼的)
这是我不明白的
- 我传递的参数的含义,我看过一些例子,但它们并没有真正传递任何参数。(中
props
constructor(props)
super(props)
) - 整个绑定代码在我看来很奇怪,
this.doNothing
改成什么?this.this.doNothing
? 它是如何工作的,为什么我的按钮知道在哪里可以找到它?
我知道这有点基本,但我确实尽了最大努力,如果有人能帮助我,我将不胜感激。
解决方案
当您使用this
关键字定义变量时,它属于 React 类的范围,因此您可以在整个 React 类的范围内使用。
我传递的参数的含义,我看过一些例子,但它们并没有真正传递任何参数。
就 bind 而言,.bind
它将上下文作为参数并返回一个函数,该函数在执行时将引用 React 类的上下文。传递给 bind 的其余参数在调用时可供函数使用。
例如当你写
constructor(props){
super(props);
this.doNothing = this.doNothing.bind(this);
}
bind 返回的函数被分配给doNothing
在类范围内定义的变量。如果您将其更改为
constructor(props){
super(props);
this.someNewFunction = this.doNothing.bind(this);
}
你会像使用它一样
render(){
<button onClick={this.someNewFunction}>I do nothing xD</button>
}
推荐阅读
- mysql - 无法在sql中的Case语句中添加关键字
- android - 从 webrtc getStats api 数据中判断是否使用了 TURN
- jquery - Jquery Onchange If else 语句不起作用
- c# - 加载 ASP.NET Core 项目时出错(自定义 C# 模型已禁用,不会从 Web 服务查询用户)
- machine-learning - 什么最适合这个模型?
- r - 安排_ggsurvplots 中的常见图例
- date - 脚本日期格式
- python - 正则表达式在一行中以大写单词开头和结尾,在大写单行单词中间有几行
- c++ - 临时对象在 C++ 中的行为如何?
- react-native - 当用户单击 react-native-paper 中的屏幕时如何关闭 Snackbar