class Table extends Component{
render(){
return(
<h2>{props.cal_months}</h2>
)
}
}
Table.defaultProps = {
cal_days :['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
cal_months : ['Jan', 'Feb', 'March', 'April',
'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec'];
daysinmonth : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
curr : new Date();
};
我正在制作日历应用。我想定义这些变量。这是在defaultProps中执行此操作的正确方法吗?
答案 0 :(得分:1)
是的,您可以在defaultProps
中定义这些值,但如果您将这些值定义为同一组件或单独文件中的常量变量会更好,因为defaultProps
将只分配默认值意味着如果您在props中传递任何更新的值,则值将被更改(覆盖)。
检查此示例:
class Table extends React.Component{
render(){
return(
<h2>{this.props.cal_months}</h2>
)
}
}
Table.defaultProps = {
cal_days :['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
cal_months : ['Jan', 'Feb', 'March', 'April',
'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec'],
daysinmonth : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
curr : new Date(),
};
ReactDOM.render(<Table/>, document.getElementById('app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
&#13;
检查在props中传递cal_days(覆盖defaultProps值):
class Table extends React.Component{
render(){
return(
<h2>{this.props.cal_months}</h2>
)
}
}
Table.defaultProps = {
cal_days :['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
cal_months : ['Jan', 'Feb', 'March', 'April',
'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec'],
daysinmonth : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
curr : new Date(),
};
ReactDOM.render(<Table cal_months={['new ', 'values']}/>, document.getElementById('app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
&#13;