Explore whether the pointer to the React component instance can be obtained outside the constructor
P粉674876385
P粉674876385 2024-04-02 22:07:22
0
1
404

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粉674876385
P粉674876385

reply all(1)
P粉018653751

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!