React-Native变量作为组件名称

时间:2016-11-10 15:15:27

标签: javascript reactjs react-native ecmascript-6

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

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

这给了我字符串'Scene1'(女巫是我的组件的名称)

之后我想要显示这样的组件

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>
        );
    }

}

1 个答案:

答案 0 :(得分:0)

我发现了同样的事情,我不确定JSX解析器应用的确切规则。我可以告诉你,这有效:

import React, { Component } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Menu.css';

class Menu extends Component {
static getInitialState() {return {show: false}};

static showModal(){
    this.setState({show: true});
};

static hideModal() {
    this.setState({show: false});
}

render() {
    if (!this.state.show) {
        return <span/>;
    }
    return (
        <Modal {...this.props} title='Meny' animation={true}>
            <div className='modal-body'>
                <ul>
                    <a href="#main"><li>Startsida</li></a>
                    <a href="#omoss"><li>Om oss </li></a>
                    <a href="#reminiscens"><li>Reminiscens</li></a>
                    <a href="#appen"><li>Appen</li></a>
                    <a href="#stories"><li>Berättelser</li></a>
                    <a href="#nyheter"><li>Nyheter om projektet</li></a>
                    <a href="#englishinfo"><li>Info in English</li></a>
                </ul>
            </div>
        </Modal>
    );
}
}
export default withStyles(s)(Menu);