属性验证是强制组件正确使用的有效方法。 这将有助于开发过程中避免未来的错误和问题,一旦应用程序变得更大。 这也使得代码更具可读性,因为我们可以看到每个组件应该如何使用。
在这个例子中,我们使用需要的所有props
来创建app组件。 app.proptypes
用于props
验证。如果某些props
没有使用指定的正确类型,那么将会得到一个控制台警告。在指定验证模式后,我们将设置app.defaultprops
。
文件:app.jsx -
import proptypes from 'prop-types';
import react from 'react';
import reactdom from 'react-dom';
class app extends react.component {
render() {
return (
<div>
<h1> hello, {this.props.name} </h1>
<h3>array: {this.props.proparray}</h3>
<h3>bool: {this.props.propbool ? "true..." : "false..."}</h3>
<h3>func: {this.props.propfunc(3)}</h3>
<h3>number: {this.props.propnumber}</h3>
<h3>string: {this.props.propstring}</h3>
</div>
);
}
}
app.proptypes = {
name: proptypes.string,
proparray: proptypes.array.isrequired,
propbool: proptypes.bool.isrequired,
propfunc: proptypes.func,
propnumber: proptypes.number,
propstring: proptypes.string,
};
app.defaultprops = {
name: 'h3.com',
proparray: [1, 2, 3, 4, 5],
propbool: true,
propfunc: function(e) {
return e
},
propnumber: 1,
propstring: "string value..."
}
export default app;
文件:main.js -
import react from 'react';
import proptypes from 'prop-types';
import reactdom from 'react-dom';
import app from './app.jsx';
reactdom.render(<app/>, document.getelementbyid('app'));
文件: webpack.config.js -
var config = {
entry: './main.js',
output: {
path:'/',
filename: 'index.js',
},
devserver: {
inline: true,
port: 8080
},
externals: {
'react': 'react'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
由于所有的props
都是有效的,会得到如下的结果。
react props验证示例
可以注意到,在验证proparray
和propbool
时,我们使用了isrequired
。如果其中一个不存在,它会给出一个错误。 如果从app.defaultprops
对象中删除proparray:[1,2,3,4,5]
,控制台将会记录一个警告。