简体   繁体   中英

Passing props from one class component to other in react js

I am taking a beginner's course on react js. I came across class components and I wanted to know how does the props object get initialized.

for eg:

Main Component:

class App extends React.Component {
    render() {
        return (
            <div>
                <Header username="xyz"/>
            </div>
        )
    }
}

Header:

class Header extends React.Component {
    render() {
        return (
            <div>
                <p>Welcome, {this.props.username}</p>
            </div>
        )
    }
}

I wanted to know does the props object in Header class is getting initialized?

Shouldn't it be something like this:

class Header extends React.Component {
    constructor(props) {
        super()
        this.props = props
    }
    render() {
        return (
            <div>
                <p>Welcome, {this.props.username}</p>
            </div>
        )
    }
}

By using the above code I am a getting a message:

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

My question is, if we want to pass anything to a class, shouldn't it be done using a constructor?

I used the same code as you post without constructor and I don't have any error.

You can pass what you want to a class without using a constructor like you did in your example code.

I share the link of your code in sandbox. I put the constructor in Header to show that it returns the same with it and without it.

By extending React.Component, React does this for you.

The props object should never be changed inside the receiving component. React class components will gather all the arguments you pass to a component, and refer to them by the common name "props". This is why you don't have to do it yourself, in the constructor.

However, in modern React, class components are rarely used. The reason is that class components easily ends up with complicated lifecycle management.

The Header component, written as a function rather than a class, would look like this:

const Header = (props) => (
  <div>
      <p>Welcome, {props.username}</p>
  </div>
)

It is also very common to destructure props directly, so that you never really access the props object, like this:

const Header = ({username}) => (
  <div>
      <p>Welcome, {username}</p>
  </div>
)

In the case of function components, you're free to use whatever name you want for the props. I wouldn't do it though, because people are used to props being called props. But this would work as well:

const Header = (params) => (
  <div>
      <p>Welcome, {params.username}</p>
  </div>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM