最近在自学react,不知道这个ref里面的this.xxx = ‘真实dom’ 这个this.xxx是什么意思?
我自己在用的时候会报错TypeError: Cannot set property this.xxx of undefined
class UnControlledForm extends Component {
handleSubmit = () => {
console.log("Input Value: ", this.input.value)
}
render () {
return (
<form onSubmit={this.handleSubmit}>
<input
type='text'
ref={(input) => this.input = input} /> <-----请问这里的this.input 是什么,在哪声明的
<button type='submit'>Submit</button>
</form>
)
}
}
首先,我这里运行你贴出来的代码是没有任何问题的,没有报错。。
这里的
this
是指你这个UnControlledForm。所以说这里的this你可以相当于一个对象来理解,我们可以对一个对象进行属性赋值。所以你这里的this.input
可以理解成:所以说这里this.input指的就是你这个input框的DOM对象。
handleSubmit
这个函数中使用了这个this.input
这个变量。一般来说一般对于这种附加在this
上的全局变量,我会现在constructor
中提前声明下,比如: