React.js
[TOC]
默認(rèn)屬性值
defaultProps 靜態(tài)屬性
<u>defaultProps</u> 可以為 <u>Class</u> 組件添加默認(rèn) <u>props</u>。這一般用于 <u>props</u> 未賦值,但又不能為 null 的情況
<span style="color:red">注意:<u>defaultProps</u> 是 <u>Class</u> 的屬性,也就是靜態(tài)屬性,不是組件實(shí)例對象的屬性</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')
);
非受控組件默認(rèn)值
有的時(shí)候,我們希望給一個(gè)非受控組件一個(gè)初始值,但是又不希望它后續(xù)通過 <u>React.js</u> 來綁定更新,這個(gè)時(shí)候我們就可以通過 <u>defaultValue</u> 或者 <u>defaultChecked</u> 來設(shè)置非受控組件的默認(rèn)值
defaultValue 屬性
<input type="text" defaultValue={this.state.v1} />
defaultChecked 屬性
<input type="checkbox" defaultChecked={this.state.v2} />
<input type="checkbox" defaultChecked={this.state.v3} />