目錄
1.默認屬性值
1.1defaultProps 靜態屬性
defaultProps 可以爲 Class 組件添加默認 props。這一般用於 props 未賦值,但又不能爲 null 的情況
注意:defaultProps 是 Class 的屬性,也就是靜態屬性,不是組件實例對象的屬性
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基於 static 的寫法
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.非受控組件默認值
有的時候,我們希望給一個非受控組件一個初始值,但是又不希望它後續通過 React.js 來綁定更新,這個時候我們就可以通過 defaultValue 或者 defaultChecked 來設置非受控組件的默認值
2.1defaultValue 屬性
<input type="text" defaultValue={this.state.v1} />
2.1defaultChecked 屬性
<input type="checkbox" defaultChecked={this.state.v2} />
<input type="checkbox" defaultChecked={this.state.v3} />