Home  >  Q&A  >  body text

Explore whether the pointer to the React component instance can be obtained outside the constructor

Consider this React component:

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

We initialize it like this:

const view = <Frame />
console.log(view)  // 在这里!

These two print statements will output:

{$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …}
constructor Frame {props: {…}, context: undefined, refs: {…}, updater: {…}}

So, I actually want the pointer to this in the constructor, but where I initialize the frame via JSX to the variable view. is it possible?

P粉674876385P粉674876385171 days ago312

reply all(1)I'll reply

  • P粉018653751

    P粉0186537512024-04-03 21:28:02

    Because the JSX <> syntax is just a sugarcane for React.createElement(Component, props, ...children)

    Your class component is initialized by React inside this function. React does not expose the value of

    this, so the pointer to it cannot be obtained

    reply
    0
  • Cancelreply