是否可以在 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/