2

在从 json 文件 ( https://www.rallyssimo.it/wp-json/wp/v2/categories )中获取某些类别后,我需要在我的应用程序的抽屉中动态放置一些项目

json 示例(我需要该信息)

[
  {
    "id": 44,
    .
    .
    "name": "ALTRI RALLY",
    .
    .
  },

这是抽屉:

const CustomDrawerComponent = (props) => (
  <SafeAreaView style={{flex:1}}>
    <View style={{height:80, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center'}}>
      <Image
        source={{uri: 'https://www.rallyssimo.it/wp-content/uploads/2016/08/rallyssimo-logo.png'}}
        style={{ height: 60, width: 180}}
      />
    </View>
    <ScrollView>
      <DrawerItems {...props} />
    </ScrollView>
  </SafeAreaView>
)
const AppNavigator = createDrawerNavigator(
  {
    Home: DashboardStackNavigator,
  },
  {
    contentComponent: CustomDrawerComponent
  }
);

const AppContainer = createAppContainer(AppNavigator);


//Main class
export default class App extends React.Component {
  render() {
    return <AppContainer />;
  }
}

如何将项目(我将从 JSON 中获取)放入抽屉中?

4

1 回答 1

2

正如您所注意到的,您需要创建自己的自定义抽屉来实现这一点,这是使用contentComponent: CustomDrawerComponent.

现在您不能DrawerItems在 CustomDrawerComponent 中使用,因为您希望完全控制列出的项目。但是您可以使用基本和元素自己重新创建项目。

最后,您需要获取 API 并将数据存储在您的状态中,以便将结果呈现为抽屉中的列表。

这是一个基本示例:

import React, { Component } from 'react';
import { ScrollView, Text, View, Image } from 'react-native';
import { NavigationActions } from 'react-navigation';


class CustomDrawerComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { data: null };
  }

  async componentDidMount() {
    fetch('https://www.rallyssimo.it/wp-json/wp/v2/categories')
      .then(res => res.json())
      .then(data => this.setState({ data }))
  }

  navigateToScreen(routeName, params) { 
    return () => { this.props.navigation.dispatch(NavigationActions.navigate({ routeName, params })) };
  }

  render() {
    if (this.state.data === null) {
      return <Text>...</Text>;
    }

    return (
      <View style={{ flex: 1, paddingTop: 30 }}>
        <View style={{height:80, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center'}}>
          <Image
            source={{uri: 'https://www.rallyssimo.it/wp-content/uploads/2016/08/rallyssimo-logo.png'}}
            style={{ height: 60, width: 180}}
          />
        </View>
        <ScrollView>
          <View>
            {this.state.data.map(x => (
              <Text
                key={x.id}
                style={{ fontSize: 16, lineHeight: 30, textAlign: 'center' }}
                onPress={this.navigateToScreen('page2')}
              >
                {x.name}
              </Text>
            ))}
          </View>
        </ScrollView>
      </View>
    );
  }
}


export default CustomDrawerComponent;

这是一份工作零食

于 2019-07-31T11:26:03.070 回答