如何将组件中的子代数限制为只有一个在本机中?

时间:2018-11-02 11:11:33

标签: react-native

我有一个接受子代的组件,我想做的就是将子代的数量限制为一个,我希望该子代是反应本机中的单个视图或单个文本

1 个答案:

答案 0 :(得分:1)

您可以使用React.Children API,特别是ABCs-Mac-mini-6:ServiceProviderApp ABCEDFC$ react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios Loading dependency graph, done. Loading dependency graph... While trying to resolve module `react-navigation-stack` from file `/Users/ABCEDFC/Desktop/react-native/New folder/ServiceProviderApp/node_modules/react-navigation/src/react-navigation.js`, the package `/Users/ABCEDFC/Desktop/react-native/New folder/ServiceProviderApp/node_modules/react-navigation/node_modules/react-navigation-stack/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/ABCEDFC/Desktop/react-native/New folder/ServiceProviderApp/node_modules/react-navigation/node_modules/react-navigation-stack/dist/index.js`. Indeed, none of these files exist: * `/Users/ABCEDFC/Desktop/react-native/New folder/ServiceProviderApp/node_modules/react-navigation/node_modules/react-navigation-stack/dist/index.js(.native||.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)` * `/Users/ABCEDFC/Desktop/react-native/New folder/ServiceProviderApp/node_modules/react-navigation/node_modules/react-navigation-stack/dist/index.js/index(.native||.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)`

我相信正确的语法是:

React.Children.only

这将验证只有一个孩子,然后返回该孩子,或者如果有多个孩子,则抛出错误。

您也可以使用class MyComponent extends React.Component { render(){ return React.Children.only(this.props.children)() } }

PropTypes

如果您想进一步证明自己的孩子只是一个class MyComponent extends React.Component { render(){ const children = this.props.children return ( <> {children} </> ) } } MyComponent.propTypes = { children: PropTypes.element.isRequired } Text实例,则可以编写一个自定义PropTypes validator,这里是一个example on StackOverflow