dynamic - React Native 是否可以动态创建组件?

标签 dynamic react-native

是否可以在 React Native 中动态创建和添加 View 组件? 例如,首先我只有空屏幕,所有 View 的信息都来自服务器的 JSON 格式,然后需要在屏幕上生成它们。 例如 - 应用程序从服务器获取 json。此 json 描述了必须构建的屏幕:

{
    "type": "linearlayout",
    "subviews": [{
        "type": "text",
        "fields": {
            "text": "This is text field"
        },
        "styles": {
            "color": "",
            "textSize": 14
        }
    }, {
        "type": "button",
        "fields": {
            "text": "JUST BUTTON"
        },
        "transition": {
            "name": "http://www.link.com"
        }
    }, {
        "type": "text",
        "fields": {
            "text": "This is another text field"
        },
        "styles": {
            "color": "",
            "textSize": 18
        }
    }]
}

因此,通过该 JSON,我需要在 React Native 中动态构建 View 。但我看不到任何在 JSX 中编写 JS 代码的能力 - 只有静态 View 和动态更改 props

最佳答案

是的,这是可能的。假设您成功检索 JSON 数据并将其保存到某种状态,然后在渲染函数中您可以像这样使用它;

render() {
    var productList = [];

        this.state.data.products.forEach(function (tmpProduct) {
            productList.push(
                <View style={cardView} key={tmpProduct.id}>

                    <Grid style={upperGrid}>
                        <Col style={{flex: 0.5}}>
                            <Thumbnail
                                source={require('../../../images/sample-image.png')}
                                style={itemThumb}>
                        </Col>
                        <Col>
                            <Text style={cardItemHeader} numberOfLines={2}>{tmpProduct.title}</Text>
                            <Text style={cardItemBody} numberOfLines={2}>{tmpProduct.description}</Text>
                        </Col>
                    </Grid>
                </View>
            );
        }.bind(this));

    return (
        <Container theme={theme}>
            <Image source={require('../../../images/grad-bg.png')} style={background} >

                <Content style={scrollContent}>

                    {productList}

                </Content>

            </Image>
        </Container>
    )
}

我希望这段代码能给您一个想法。您可以根据您的情况进行调整。

关于dynamic - React Native 是否可以动态创建组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42053237/

相关文章:

android - 如何修复以下错误 : A problem occurred evaluating project ':app' . > 没有方法签名:

ios - 从 UIImageView 派生的动态创建的控件缺少函数

动态创建后未应用完整 CSS 的 Jquery Mobile 复选框 radio

jquery - 动态设置多个 div 背景图像与第三个父 div 相同

javascript - React Native 怪异的 flex 行为

react-native - React Native - 每封邮件发送照片

javascript - 如何使用组件将动态 HTML 加载到 DIV 中? Angular 5

macos - 在 OSX 中动态更新应用程序图标

javascript - 如何在 React-Native 应用程序中处理对 Firebase 的异步调用?

ios - React Native iOS 发布版本链接问题