From d5aec619b1476017e1c966708ecbae60f2398897 Mon Sep 17 00:00:00 2001 From: ycjcl868 <45808948@qq.com> Date: Sun, 17 Feb 2019 16:47:43 +0800 Subject: [PATCH] :memo: docs/typechecking-with-proptypes.md --- content/docs/typechecking-with-proptypes.md | 78 ++++++++++----------- 1 file changed, 37 insertions(+), 41 deletions(-) diff --git a/content/docs/typechecking-with-proptypes.md b/content/docs/typechecking-with-proptypes.md index 4004e7820c..ddacf49d46 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 15.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,17 @@ 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`。当传入类型不正确的属性时,JavaScript 控制台将会显示警告。出于性能方面的考虑,`propTypes` 只仅在开发模式下进行检查。 -### PropTypes {#proptypes} +### Prop 类型 {#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 +49,47 @@ 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. + // 你也可以声明属性为某个类的实例,这里使用 JS 的 instanceof 操作符。 optionalMessage: PropTypes.instanceOf(Message), - // You can ensure that your prop is limited to specific values by treating - // it as an enum. + // 你可以使你的属性只接收指定的值。 + // 这是一个枚举类型。 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` ,确保这个属性父组件没有提供时,会打印警告信息。 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 +99,10 @@ 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 +114,17 @@ 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 +139,9 @@ MyComponent.propTypes = { }; ``` -### Default Prop Values {#default-prop-values} +### 属性默认值 {#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 +152,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 +180,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`。