React (c) - The default value of the component attribute React

table of Contents

1. Default property values

1.1defaultProps static properties

1.1.1 based on static wording

2. uncontrolled default value components

2.1defaultValue property

2.1defaultChecked property


1. Default property values

1.1defaultProps static properties

defaultProps can be a Class added default component props . This is generally used for props unassigned, but can not be null in case

Note: defaultProps  is the  Class  property, which is property Static property, not the component instance of an object

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return(
            <div>
                <h2>MyComponent - {this.props.max}</h2>
            </div>
        );
    }
}

MyComponent.defaultProps = {
    max: 10
}

ReactDOM.render(
    <MyComponent />,
    document.getElementById('app')
);

1.1.1 based on static wording

class MyComponent extends React.Component {
  	static defaultProps = {
      	max: 10
    }
    constructor(props) {
        super(props);
    }

    render() {
        return(
            <div>
                <h2>MyComponent - {this.props.max}</h2>
            </div>
        );
    }
}

ReactDOM.render(
    <MyComponent />,
    document.getElementById('app')
);

2. uncontrolled default value components

Sometimes, we want to give a non-controlled components of an initial value, but do not want it to follow through React.js to bind update, this time we can defaultValue or defaultChecked to set the default value of non-controlled components

2.1defaultValue property

<input type="text" defaultValue={this.state.v1} />

2.1defaultChecked property

<input type="checkbox" defaultChecked={this.state.v2}  />
<input type="checkbox" defaultChecked={this.state.v3}  />

 

Published 95 original articles · won praise 115 · views 120 000 +

Guess you like

Origin blog.csdn.net/qq_34569497/article/details/105209448