如何解决将组件添加到View React Native
我对React Native还是很陌生,所以请原谅一些不良做法(请指出)。
我目前正在尝试在React组件安装后动态加载按钮。之所以这样做,是在组件加载后立即调用API,该API请求一个具有我需要显示给用户的值的数组。
我设法检索了数组并在其上循环,但是我没有设法在当前屏幕上显示按钮。
我的代码是这样:
export default class Menu extends React.Component {
constructor(props) {
super(props);
this.state = {
token : "",unique_id : Constants.deviceId,qr_value : props.route.params.random_value,buttons : []
}
}
componentDidMount(){
this.testToken();
}
然后,我有了render函数,该函数创建一个View并调用getButtons()函数
render() {
return (
<View style={styles.container}>
<View style={styles.header} >
{this.getButtons()}
</View>
</View>
);
}
getButtons函数调用上面提到的API,检索对象数组并将该数组的值分配给this.state.buttons。我已从请求中删除了这些值。
getButtons(token) {
fetch('link hidden',{
method: 'POST',}).then(response => response.json().then(data =>({
data: data,status: response.status
})
).then(res => {
this.state.buttons = res.data.options;
// this.buttons = this.state.buttons.map((item,key) =>
// console.log(item)
// );
this.renderButtons();
}));
}
renderButtons函数然后调用这些:
renderButton(button) {
return (
<TouchableOpacity
style = {{backgroundColor: '#fff'}}
onPress = {
() => this.generateToken()
}
>
<View style={styles.button}>
<Text style={styles.title}>{button.value}</Text>
</View>
</TouchableOpacity>
);
}
renderButtons = buttons => {
return this.state.buttons.map((button,i) => {
return (
<View key={i}>
{this.renderButton(button)}
</View>
);
});
}
任何帮助或建议都非常受欢迎。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。