diff --git a/content/docs/typechecking-with-proptypes.md b/content/docs/typechecking-with-proptypes.md index 4004e7820c..70fa1f433c 100644 --- a/content/docs/typechecking-with-proptypes.md +++ b/content/docs/typechecking-with-proptypes.md @@ -1,18 +1,18 @@ --- id: typechecking-with-proptypes -title: Typechecking With PropTypes +title: 使用 PropTypes 进行类型检查 permalink: docs/typechecking-with-proptypes.html redirect_from: - "docs/react-api.html#typechecking-with-proptypes" --- -> Note: +> 注意: > -> `React.PropTypes` has moved into a different package since React v15.5. Please use [the `prop-types` library instead](https://www.npmjs.com/package/prop-types). +> 自 React v15.5 起,`React.PropTypes` 已移入另一个包中。请使用 [`prop-types` 库](https://www.npmjs.com/package/prop-types) 代替。 > ->We provide [a codemod script](/blog/2017/04/07/react-v15.5.0.html#migrating-from-reactproptypes) to automate the conversion. +>我们提供了一个 [codemod 脚本](/blog/2017/04/07/react-v15.5.0.html#migrating-from-reactproptypes)来做自动转换。 -As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript extensions like [Flow](https://flow.org/) or [TypeScript](https://www.typescriptlang.org/) to typecheck your whole application. But even if you don't use those, React has some built-in typechecking abilities. To run typechecking on the props for a component, you can assign the special `propTypes` property: +随着你的应用程序不断增长,你可以通过类型检查捕获大量错误。对于某些应用程序来说,你可以使用 [Flow](https://flow.org/) 或 [TypeScript](https://www.typescriptlang.org/) 等 JavaScript 扩展来对整个应用程序做类型检查。但即使你不使用这些扩展,React 也内置了一些类型检查的功能。要在组件的 props 上进行类型检查,你只需配置特定的 `propTypes` 属性: ```javascript import PropTypes from 'prop-types'; @@ -30,18 +30,18 @@ Greeting.propTypes = { }; ``` -`PropTypes` exports a range of validators that can be used to make sure the data you receive is valid. In this example, we're using `PropTypes.string`. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. For performance reasons, `propTypes` is only checked in development mode. +`PropTypes` 提供一系列验证器,可用于确保组件接收到的数据类型是有效的。在本例中, 我们使用了 `PropTypes.string`。当传入的 `prop` 值类型不正确时,JavaScript 控制台将会显示警告。出于性能方面的考虑,`propTypes` 仅在开发模式下进行检查。 ### PropTypes {#proptypes} -Here is an example documenting the different validators provided: +以下提供了使用不同验证器的例子: ```javascript import PropTypes from 'prop-types'; MyComponent.propTypes = { - // You can declare that a prop is a specific JS type. By default, these - // are all optional. + // 你可以将属性声明为 JS 原生类型,默认情况下 + // 这些属性都是可选的。 optionalArray: PropTypes.array, optionalBool: PropTypes.bool, optionalFunc: PropTypes.func, @@ -50,50 +50,49 @@ MyComponent.propTypes = { optionalString: PropTypes.string, optionalSymbol: PropTypes.symbol, - // Anything that can be rendered: numbers, strings, elements or an array - // (or fragment) containing these types. + // 任何可被渲染的元素(包括数字、字符串、元素或数组) + // (或 Fragment) 也包含这些类型。 optionalNode: PropTypes.node, - // A React element. + // 一个 React 元素。 optionalElement: PropTypes.element, - // You can also declare that a prop is an instance of a class. This uses - // JS's instanceof operator. + // 你也可以声明 prop 为类的实例,这里使用 + // JS 的 instanceof 操作符。 optionalMessage: PropTypes.instanceOf(Message), - // You can ensure that your prop is limited to specific values by treating - // it as an enum. + // 你可以让你的 prop 只能是特定的值,指定它为 + // 枚举类型。 optionalEnum: PropTypes.oneOf(['News', 'Photos']), - // An object that could be one of many types + // 一个对象可以是几种类型中的任意一个类型 optionalUnion: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(Message) ]), - // An array of a certain type + // 可以指定一个数组由某一类型的元素组成 optionalArrayOf: PropTypes.arrayOf(PropTypes.number), - // An object with property values of a certain type + // 可以指定一个对象由某一类型的值组成 optionalObjectOf: PropTypes.objectOf(PropTypes.number), - // An object taking on a particular shape + // 可以指定一个对象由特定的类型值组成 optionalObjectWithShape: PropTypes.shape({ color: PropTypes.string, fontSize: PropTypes.number }), - // You can chain any of the above with `isRequired` to make sure a warning - // is shown if the prop isn't provided. + // 你可以在任何 PropTypes 属性后面加上 `isRequired` ,确保 + // 这个 prop 没有被提供时,会打印警告信息。 requiredFunc: PropTypes.func.isRequired, - // A value of any data type + // 任意类型的数据 requiredAny: PropTypes.any.isRequired, - // You can also specify a custom validator. It should return an Error - // object if the validation fails. Don't `console.warn` or throw, as this - // won't work inside `oneOfType`. + // 你可以指定一个自定义验证器。它在验证失败时应返回一个 Error 对象。 + // 请不要使用 `console.warn` 或抛出异常,因为这在 `onOfType` 中不会起作用。 customProp: function(props, propName, componentName) { if (!/matchme/.test(props[propName])) { return new Error( @@ -103,11 +102,11 @@ MyComponent.propTypes = { } }, - // You can also supply a custom validator to `arrayOf` and `objectOf`. - // It should return an Error object if the validation fails. The validator - // will be called for each key in the array or object. The first two - // arguments of the validator are the array or object itself, and the - // current item's key. + // 你也可以提供一个自定义的 `arrayOf` 或 `objectOf` 验证器。 + // 它应该在验证失败时返回一个 Error 对象。 + // 验证器将验证数组或对象中的每个值。验证器的前两个参数 + // 第一个是数组或对象本身 + // 第二个是他们当前的键。 customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) { if (!/matchme/.test(propValue[key])) { return new Error( @@ -119,16 +118,16 @@ MyComponent.propTypes = { }; ``` -### Requiring Single Child {#requiring-single-child} +### 限制单个元素 {#requiring-single-child} -With `PropTypes.element` you can specify that only a single child can be passed to a component as children. +你可以通过 `PropTypes.element` 来确保传递给组件的 children 中只包含一个元素。 ```javascript import PropTypes from 'prop-types'; class MyComponent extends React.Component { render() { - // This must be exactly one element or it will warn. + // 这必须只有一个元素,否则控制台会打印警告。 const children = this.props.children; return (
@@ -143,9 +142,9 @@ MyComponent.propTypes = { }; ``` -### Default Prop Values {#default-prop-values} +### 默认 Prop 值 {#default-prop-values} -You can define default values for your `props` by assigning to the special `defaultProps` property: +您可以通过配置特定的 `defaultProps` 属性来定义 `props` 的默认值: ```javascript class Greeting extends React.Component { @@ -156,19 +155,19 @@ class Greeting extends React.Component { } } -// Specifies the default values for props: +// 指定 props 的默认值: Greeting.defaultProps = { name: 'Stranger' }; -// Renders "Hello, Stranger": +// 渲染出 "Hello, Stranger": ReactDOM.render( , document.getElementById('example') ); ``` -If you are using a Babel transform like [transform-class-properties](https://babeljs.io/docs/plugins/transform-class-properties/) , you can also declare `defaultProps` as static property within a React component class. This syntax has not yet been finalized though and will require a compilation step to work within a browser. For more information, see the [class fields proposal](https://github.com/tc39/proposal-class-fields). +如果你正在使用像 [transform-class-properties](https://babeljs.io/docs/plugins/transform-class-properties/) 的 Babel 转换工具,你也可以在 React 组件类中声明 `defaultProps` 作为静态属性。此语法提案还没有最终确定,需要进行编译后才能在浏览器中运行。要了解更多信息,请查阅 [class fields proposal](https://github.com/tc39/proposal-class-fields)。 ```javascript class Greeting extends React.Component { @@ -184,4 +183,4 @@ class Greeting extends React.Component { } ``` -The `defaultProps` will be used to ensure that `this.props.name` will have a value if it was not specified by the parent component. The `propTypes` typechecking happens after `defaultProps` are resolved, so typechecking will also apply to the `defaultProps`. +`defaultProps` 用于确保 `this.props.name` 在父组件没有指定其值时,有一个默认值。`propTypes` 类型检查发生在 `defaultProps` 赋值后,所以类型检查也适用于 `defaultProps`。