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} />