当我使用expo运行react native应用程序时,出现以下错误。
我收到以下错误。
Invariant Violation: Objects are not valid as a React child (found: object with keys {text, onPress}). If you meant to render a collection of children, use an array instead.
in RCTText (at Text.js:154)
in TouchableText (at Text.js:278)
in Text (at ClearButton.js:10)
in RCTView (at View.js:45)
in View (at ClearButton.js:8)
in RCTView (at View.js:45)
in View (at createAnimatedComponent.js:151)
in AnimatedComponent (at TouchableOpacity.js:282)
in TouchableOpacity (at ClearButton.js:7)
in ClearButton (at Home.js:49)
in RCTView (at View.js:45)
in View (at Container.js:8)
in Container (at Home.js:33)
in Home (at app/index.js:9)
in _default (at withExpoRoot.js:20)
in RootErrorBoundary (at withExpoRoot.js:19)
in ExpoRootComponent (at renderApplication.js:35)
in RCTView (at View.js:45)
in View (at AppContainer.js:98)
in RCTView (at View.js:45)
in View (at AppContainer.js:115)
in AppContainer (at renderApplication.js:34)
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:8070:6 in throwOnInvalidObjectType
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:9133:31 in reconcileChildFibers
- ... 20 more stack frames from framework internals
我在该课程上拥有的代码是。我不知道以下代码有什么问题。请帮忙。
import React from 'react';
import { TouchableOpacity, View, Text, Image} from 'react-native';
import PropTypes from 'prop-types';
import styles from './styles';
const ClearButton = (text, onPress) => (
<TouchableOpacity onPress={onPress}>
<View>
<Image source={require('./images/logo.png')} />
<Text>{text}</Text>
</View>
</TouchableOpacity>
);
ClearButton.PropTypes ={
text : PropTypes.string,
onPress : PropTypes.fun,
};
export default ClearButton;
答案 0 :(得分:3)
React的功能组件将props作为第一个参数接收:
const ClearButton = (props) => {
// get keys in props
const text = props.text;
const onPress = props.onPress
...
}
因此,如果要使用分解结构进行编写,则可以这样重写组件:
const ClearButton = ({ text, onPress }) => ( // use destructuring here
<TouchableOpacity onPress={onPress}>
<View>
<Image source={require('./images/logo.png')} />
<Text>{text}</Text>
</View>
</TouchableOpacity>
);