一般设置props的默认值有两种方式,下面通过一个例子说明一下。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React表单</title>
<script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
class Greeting extends React.Component {
//方法一: 指定 props 的默认值, 这个方法只有浏览器编译以后 才会生效
static defaultProps = {
age: 18
}
render() {
return (
<h1>Hello, {this.props.name}. and my age is {this.props.age}</h1>
);
}
}
// 方法二: 指定 props 的默认值,这个方法会一直生效
Greeting.defaultProps = {
name: '我是props的默认值!'
};
ReactDOM.render(
<Greeting />,
document.getElementById('example')
);
</script>
</body>
</html>
第一种方式:
React 组件类中声明 defaultProps 作为静态属性。
第二种方式:
通过赋值特定的 defaultProps 属性为 props 定义默认值: