【问题标题】:The component for route '...' must be a React component路由“...”的组件必须是 React 组件
【发布时间】:2019-08-06 09:22:55
【问题描述】:

我有一个 React 组件 (Highlight.js),它接受两个属性,imagedescription。用户将使用自己的背景图像和描述在 4 个不同的屏幕上滑动,作为对应用程序的介绍。

TestScreen.js 是我设置在屏幕之间导航的逻辑的地方。当我尝试将 AppContainer 中的屏幕设置为 Highlight 组件时,我不断收到错误消息,即“路由 'Page1' 的组件必须是 React 组件。

我尝试了很多代码,看看我如何设法让它工作,唯一的方法是当我没有提到图像和描述属性时,在这种情况下都不会显示而且屏幕大部分是空白的。

Highlight.js

import React, { Component } from 'react';
import { View, Text, Image, ImageBackground } from 'react-native';

import { NextButton } from '../Buttons';

import styles from './styles';

export default class Highlight extends Component {
  render() {
    return (
      <ImageBackground style={styles.container}>
        <Image
          style={styles.image}
          source={this.props.image} // the image goes here
          resizeMode="cover"
        />
        <View style={styles.textContainer}>
          <Text style={styles.text1}>MYAPP</Text>
          <Text style={styles.text2}>Highlights</Text>
          <Text style={styles.text3}>{this.props.description}</Text> // the description goes here
        </View>
        <View style={styles.buttonContainer}>
          <NextButton />
        </View>
      </ImageBackground>
    );
  }
}

TestScreen.js

import React, { Component } from 'react';
import { createAppContainer, createStackNavigator } from 'react-navigation';

import { Highlight } from '../components/Highlights';

export default class TestScreen extends Component {
  render() {
    return <AppContainer />;
  }
}

const AppContainer = createAppContainer(
  createStackNavigator({
    Page1: {
      screen: (
        <Highlight
          image={require('../components/Highlights/images/highlight1.png')}
          description={
            'Avoid No-Show of Candidates after setting up an interview'
          }
        />
      )
    }
  })
);

我希望屏幕显示带有图像和描述属性的内容。目前我有 4 个独立的组件,它们的代码基本相同(图像和描述除外)。如何解决这个问题,避免代码重复?

【问题讨论】:

  • 试屏:() => ()
  • 我可以发誓我试过了。也许我错过了一些东西,但你在先生身上。这让它像魅力一样工作。非常感谢!

标签: react-native react-navigation


【解决方案1】:

简要说明

您将元素传递给路由而不是组件本身

() => (<Highlight ... />)

这会创建一个新的函数组件,它会返回您期望的元素, 这就是它起作用的原因

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    相关资源
    最近更新 更多