Nat*_*ein 12 dynamic react-native
是否可以在React Native中动态创建和添加视图组件?例如,首先我只有空屏幕,所有视图的信息都来自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
}
}]
}
Run Code Online (Sandbox Code Playgroud)
所以,通过JSON,我需要在React Native中动态构建视图.但我看不到任何在JSX中编写JS代码的能力 - 只有静态视图和动态更改道具
mil*_*rac 13
是的,这是可能的.假设您成功检索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>
)
}
Run Code Online (Sandbox Code Playgroud)
我希望这段代码能给你一个想法.您可以根据您的情况进行调整.
React 文档(通过扩展也可以使用 ReactNative 完成)展示了如何在运行时选择组件类型:
import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
photo: PhotoStory,
video: VideoStory
};
function Story(props) {
const SpecificStory = components[props.storyType];
return <SpecificStory story={props.story} />;
}
Run Code Online (Sandbox Code Playgroud)
这样做,您只需要在 JSON 树上行走并创建 ReactNative 组件,使用该components对象作为 JSON 树中定义的类型与其构造函数之间的映射。
是的,可以根据从服务器检索的数据在 React Native 中动态创建组件。
但是,如果您希望应用程序检查最新的 JS 代码(包括新组件/视图)而不需要通过应用程序商店进行更新,您可以使用代码推送之类的东西。https://microsoft.github.io/code-push/
你的问题有点模糊,所以如果我误解了,那么你可能可以举一个例子“所有观点的信息”。
| 归档时间: |
|
| 查看次数: |
12840 次 |
| 最近记录: |