是否可以在React Native中动态渲染组件?

时间:2019-04-24 07:53:19

标签: json react-native react-native-android

是否可以动态创建组件并在React-Native中渲染它们?我想从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
        }
    }]
}

1 个答案:

答案 0 :(得分:0)

根据您的要求,首先您必须将所有必需的元素手动导入到页面中,然后您需要创建一个带有空白数组的状态,然后在已装入组件或要渲染数据的任何位置调用循环

在循环内,根据元素创建条件,并传递动态值,无论您从json文件中获得什么。

var data = {
    "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
        }
    }]
}

import {
    View,
    TextInput,
    Button,
} from 'react-native';


constructor(props){
    super(props);
    this.state = {
        itemstorender: [],
    }
}

componentDidMount() {
    this.renderData();
}

renderData = () => {
    for(var i = 0; i<data.subviews.length; i++){
        if(data.subviews[i].type == "text"){
            this.setState({
                itemstorender: this.state.itemstorender.concat([
                    <TextInput
                        style = {data.subviews[i].styles}
                        placeholder = data.subviews[i].fields.text
                    />
                ])
            })
        }else if(data.subviews[i].type == "button"){
            this.setState({
                itemstorender: this.state.itemstorender.concat([
                    <Button
                      onPress={alert('ok')}
                      title=data.subviews[i].fields.text
                    />
                ])
            })
        }
    }
}

render() {
    return (
        <View>
            { this.state.itemstorender }
        </View>
    )
}