Why do react components define a default state

problem description

I"d like to ask you why the react component defines defaultProps,displayName,. If it"s not defined, what"s wrong with it?

the environmental background of the problems and what methods you have tried

tried it and found that there would be no problem

related codes

/ / Please paste the code text below (do not replace the code with pictures)

Component.displayName = "CreateUser";

Component.defaultProps = {
className: "createUser",
};

what result do you expect? What is the error message actually seen?

I hope you can help answer

Jul.06,2021

DefaultProps in

React is not the default state, it is the default property. Write a simple example:

class Title extends React.Component{
  render(){
    const { title, color } = this.props;
    return(
      <div>
        <h3 style={{ color: color }}>
          {title}
        </h3>
      </div>
    );
  };
};
Title.defaultProps = {
  color: '-sharp666',
  title: '',
};

ReactDOM.render(
  <Title />,
  document.getElementById('root')
);
The function of the default property is to have a default value when you call the component without passing in the corresponding property value. It is not defined and will not report an error, but it is best to pass in all the required property values when calling the component, otherwise an error may occur.


I'm just here to add.

because the new version of babel supports transform-class-properties to convert, the syntax will be changed to add static to define it. Here is the sample code of the official document:

  https://reactjs.org/docs/type.

Menu