6-React 組件之屬性默認值

React.js

[TOC]

默認屬性值

defaultProps 靜態屬性

<u>defaultProps</u> 可以為 <u>Class</u> 組件添加默認 <u>props</u>。這一般用于 <u>props</u> 未賦值,但又不能為 null 的情況

<span style="color:red">注意:<u>defaultProps</u> 是 <u>Class</u> 的屬性,也就是靜態屬性,不是組件實例對象的屬性</span>

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')
);
基于 <u>static</u> 的寫法
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')
);

非受控組件默認值

有的時候,我們希望給一個非受控組件一個初始值,但是又不希望它后續通過 <u>React.js</u> 來綁定更新,這個時候我們就可以通過 <u>defaultValue</u> 或者 <u>defaultChecked</u> 來設置非受控組件的默認值

defaultValue 屬性

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

defaultChecked 屬性

<input type="checkbox" defaultChecked={this.state.v2}  />
<input type="checkbox" defaultChecked={this.state.v3}  />
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容