考虑这个React组件:
import React, { Component } from 'react'
class Frame extends Component {
constructor(props) {
super(props)
console.log('constructor', this) // 我想要 *this* 但是 ...
}
render() {
return <p></p>
}
}
export default Frame
我们这样初始化它:
const view = <Frame /> console.log(view) // 在这里!
这两个打印语句会输出:
{$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …}
constructor Frame {props: {…}, context: undefined, refs: {…}, updater: {…}}
所以,我实际上想要在构造函数中的指针this,但是在我通过JSX将frame初始化为变量view的地方。这可能吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
由于JSX
<>语法只是对React.createElement(Component, props, ...children)的合成糖你的类组件在该函数内部由React进行初始化,React不会公开
this的值,因此无法获取指向它的指针