- Objective:
- Breadcrumb:
# 概念阐释
## 语义
当`props`为空时,可以显示默认参数来填补。
## 语法
可以有 3 种写法。
```jsx
// 通过添加解构函数
function Example(props) {
const {text = 'this is default value'} = props;
return <h1>{text}</h1>
}
// 将解构函数作为参数
function Example({text = 'this is default value'}) {
return <h1>{text}</h1>
}
// 添加静态属性
function Example(props) {
return <h1>{props.text}</h1>
}
Example.defaultProps = {
text: 'This is default text',
};
```
# 实例
在 text 中没有值
```jsx
//App.js
import React from 'react';
import Button from './Button.js';
function App() {
return <Button text=""/>;
}
export default App
```
在 button 中加入 default props
```jsx
import React from 'react';
function Button(props) {
const {text = 'Default Text of Big Button'} = props;
return (
<button>{text}</button>
);
}
export default Button;
```
# 相关内容
# 参考资料
- [Giving Default Values to props](https://www.codecademy.com/journeys/full-stack-engineer/paths/fscj-22-front-end-development/tracks/fscj-22-react-part-ii/modules/wdcp-22-components-interacting-218cf398-22f2-4666-97bc-52d6789f0a78/lessons/this-props/exercises/defaultprops)