【发布时间】:2017-05-24 02:17:56
【问题描述】:
希望下面的脚本能大致显示我想要实现的目标。
但本质上,使用存储在状态中的字符串,能够让组件持有者在更改时动态加载不同的组件。
因此您会在顶部看到 2 个导入的组件(但理想情况下,这些组件可能是 100 个不同的组件。
一个currentSlide 状态,包含组件的字符串名称。
还有一个 SlideLoader 组件,它可以根据字符串名称理想地加载导入的组件。
然后按钮通过重置状态名称来切换组件。
谢谢!
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
} from 'react-native';
import SlideA from './slideA';
import SlideB from './slideB';
const styles = StyleSheet.create({
dummyContainer: {
flex: 0,
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: '#999999',
},
buttonHolder: {
position: 'absolute',
top: 4,
left: 0,
},
button: {
height: 50,
width: 300,
backgroundColor: 'red',
marginBottom: 4,
textAlignVertical: 'center',
textAlign: 'center',
fontWeight: 'bold',
},
});
export default class Switcher extends Component {
constructor(props, context) {
super(props, context);
let state = {
currentSlide: 'SlideA',
}
}
render() {
// obvisously wrong part...
let SlideLoader = this.state.currentSlide;
// end of obvisously wrong part...
return (
<View
style={[
styles.dummyContainer,
]}
>
<SlideLoader />
<View
style={styles.buttonHolder}
>
<Text
onPress={() => {
console.log('SLID A');
setState({ currentSlide: 'SlideA' });
}}
style={[styles.button]}
>
Slide A
</Text>
<Text
onPress={() => {
console.log('SLID B');
setState({ currentSlide: 'SlideB' });
}}
style={[styles.button]}
>
Slide B
</Text>
</View>
</View>
);
}
}
【问题讨论】:
标签: string reactjs dynamic components