【问题标题】:React-Native variable as component nameReact-Native 变量作为组件名称
【发布时间】:2016-11-10 15:15:27
【问题描述】:

我正在尝试使用 react-native 构建一个应用程序。我有多个类,我想根据状态显示一个类。

let MyComponent = this.props.navigationState.routes[this.props.navigationState.index].component;

这给了我字符串“Scene1”(witch 是我的组件的名称)

之后我想像这样显示组件

return <MyComponent />;

我收到了错误:

期望一个组件类,得到[object Object]。

如果我这样显示组件:

return <Scene1 />;

它实际上显示了我的组件。

有人知道这两个例子有什么区别吗?我不明白为什么包含字符串的变量与字符串不同。也许我错过了一个非常小的细节,但我只是不知道这里出了什么问题

编辑: 根据要求我的路线

class Scene1 extends Component {

    render() {

        return(
            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'yellow'}}>
                <Text>Scene1</Text>
                <View>
                    <Text onPress={ () => this.props.navigate({ type: 'push', key: 'scene2' })}>Go to Scene2</Text>
                </View>
            </View>
        );
    }

}

【问题讨论】:

  • 你可以在这里添加你的路线
  • 更新了我的帖子,你是这个意思吗?
  • 你能在this.props.navigationState.routes[this.props.navigationState.index]this.props.navigationState 上做一个console.log 吗?并添加您定义navigationState 的文件?此错误意味着您将对象而不是函数/类作为MyComponent 传递,这让我认为无论您设置navigationState.routes.component,您使用的是字符串而不是实际的类。
  • @vanBrunneren 不,我的意思是 navigationState.routes[..]
  • @TuckerConnelly 就像你描述的那样,我使用的是字符串而不是实际的类。感谢您的帮助

标签: javascript reactjs react-native ecmascript-6


【解决方案1】:

我发现了同样的事情,我不确定 JSX 解析器到底应用了什么规则。我可以告诉你这是可行的:

<this.props.componentClass />

【讨论】:

  • 是的,这是可能的并且有效,但是您不能像我想对我的 this.props.navigationState.routes[this.props.navigationState .index].component
猜你喜欢
  • 2012-05-09
  • 2019-02-21
  • 2019-05-27
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 2019-11-09
  • 1970-01-01
相关资源
最近更新 更多