?
This document uses PHP Chinese website manual Release
注意:
React.PropTypes
自從React v15.5以來(lái),它已經(jīng)進(jìn)入了一個(gè)不同的包。請(qǐng)使用該prop-types
庫(kù),而不是。我們提供了一個(gè)codemod腳本來(lái)自動(dòng)化轉(zhuǎn)換。
隨著您的應(yīng)用程序的增長(zhǎng),您可以通過(guò)類型檢查來(lái)捕捉大量錯(cuò)誤。對(duì)于某些應(yīng)用程序,您可以使用JavaScript擴(kuò)展(如Flow或TypeScript)來(lái)檢查整個(gè)應(yīng)用程序。但即使你不使用這些,React也有一些內(nèi)置的類型檢測(cè)功能。要在組件的道具上運(yùn)行類型檢查,可以指定特殊propTypes
屬性:
import PropTypes from 'prop-types'; class Greeting extends React.Component { render() { return ( <h1>Hello, {this.props.name}</h1> ); }} Greeting.propTypes = { name: PropTypes.string};
PropTypes
導(dǎo)出一系列可用于確保您收到的數(shù)據(jù)有效的驗(yàn)證程序。在這個(gè)例子中,我們正在使用PropTypes.string
。當(dāng)為prop提供無(wú)效值時(shí),JavaScript控制臺(tái)中將顯示警告。出于性能原因,propTypes
僅在開(kāi)發(fā)模式下進(jìn)行檢查。
這里是一個(gè)記錄提供的不同驗(yàn)證器的例子:
import PropTypes from 'prop-types'; MyComponent.propTypes = { // You can declare that a prop is a specific JS primitive. By default, these // are all optional. optionalArray: PropTypes.array, optionalBool: PropTypes.bool, optionalFunc: PropTypes.func, optionalNumber: PropTypes.number, optionalObject: PropTypes.object, optionalString: PropTypes.string, optionalSymbol: PropTypes.symbol, // Anything that can be rendered: numbers, strings, elements or an array // (or fragment) containing these types. optionalNode: PropTypes.node, // A React element. optionalElement: PropTypes.element, // You can also declare that a prop is an instance of a class. This uses // JS's instanceof operator. 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. 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`. customProp: function(props, propName, componentName) { if (!/matchme/.test(props[propName])) { return new Error( 'Invalid prop `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.' ); } }, // 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. customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) { if (!/matchme/.test(propValue[key])) { return new Error( 'Invalid prop `' + propFullName + '` supplied to' + ' `' + componentName + '`. Validation failed.' ); } })};
隨著PropTypes.element
您可以指定只有一個(gè)孩子可以傳遞給兒童一個(gè)組成部分。
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 ( <div> {children} </div> ); }} MyComponent.propTypes = { children: PropTypes.element.isRequired };
您可以props
通過(guò)分配特殊defaultProps
屬性來(lái)為您定義默認(rèn)值:
class Greeting extends React.Component { render() { return ( <h1>Hello, {this.props.name}</h1> ); }} // Specifies the default values for props: Greeting.defaultProps = { name: 'Stranger'};// Renders "Hello, Stranger":ReactDOM.render( <Greeting />, document.getElementById('example'));
如果使用類似transform-class-properties的Babel變換,則還可以defaultProps
在React組件類中聲明為靜態(tài)屬性。盡管這個(gè)語(yǔ)法尚未完成,并且需要編譯步驟才能在瀏覽器中工作。有關(guān)更多信息,請(qǐng)參閱班級(jí)字段提案。
class Greeting extends React.Component { static defaultProps = { name: 'stranger' } render() { return ( <div>Hello, {this.props.name}</div> ) }}
的defaultProps
將被用于確保this.props.name
,如果不是由父組件指定它將有一個(gè)值。類型檢查propTypes
發(fā)生在defaultProps
解決后,因此類型檢查也將適用于該類型defaultProps
。