明确检查 React Component 收到必要的道具?
Explicitly check React Component received necessary props?
React Component 可能会从调用者(parent)接收一组参数(props)。是否有一种机制来检查是否只传递了必要的道具(不多不少)?
我知道我们可以在运行时在构造函数中检查这些东西,但这是一种资源浪费。有没有办法在 构建时检查这些东西?
您可能正在寻找 proptypes
下面的例子取自上面 link:
import PropTypes from 'prop-types';
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Greeting.propTypes = {
name: PropTypes.string.isRequired
};
在上面的例子中,无论你在哪里使用 Greeting
组件,你都应该发送一个类型为 string
的道具 name
。否则您的应用程序将无法 运行.
此检查将在开发阶段自行完成,以便我们可以进行必要的更改以发送正确的道具
React Component 可能会从调用者(parent)接收一组参数(props)。是否有一种机制来检查是否只传递了必要的道具(不多不少)?
我知道我们可以在运行时在构造函数中检查这些东西,但这是一种资源浪费。有没有办法在 构建时检查这些东西?
您可能正在寻找 proptypes
下面的例子取自上面 link:
import PropTypes from 'prop-types';
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Greeting.propTypes = {
name: PropTypes.string.isRequired
};
在上面的例子中,无论你在哪里使用 Greeting
组件,你都应该发送一个类型为 string
的道具 name
。否则您的应用程序将无法 运行.
此检查将在开发阶段自行完成,以便我们可以进行必要的更改以发送正确的道具