【问题标题】:React Native different categories rendered to header componentReact Native 不同类别渲染到标题组件
【发布时间】:2018-05-06 19:18:35
【问题描述】:

我正在开发一个 React Native 测验应用程序。我已经开发了 header 组件,它看起来很棒。

// import libraries for making a component
import React from 'react';
import { Text, View } from 'react-native';

// make a component
const Header = (props) => {
  const { textStyle, viewStyle } = styles;
  return (
    <View style={viewStyle}>
      <Text style={textStyle}>{props.headerText}</Text>;
    </View>
  );
};

const styles = {
  viewStyle: {
    backgroundColor: '#F8F8F8',
    justifyContent: 'center',
    alignItems: 'center',
    height: 60,
    paddingTop: 15,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    elevation: 2,
    position: 'relative'
  },
  textStyle: {
    fontSize: 20
  }
};

// make a component available to other parts of the app
export default Header;

我将向具有类别的 api 发出 ajax 请求,然后每个类别有一个测验问题。

当我向这个端点发出 GET 请求时,我会返回一组对象,每个对象都有一个问题类别和一个布尔问题,即真假。

所以我总共有 10 个类别,每个类别有一个问题,总共 10 个问题。

所以我需要弄清楚如何从我的移动应用程序发出 Ajax 请求或 http 请求来获取这个数据列表,更关键的是,一旦我有了数据列表,我需要找到一种方法来获取要呈现为标题的类别片段。

这是我坚持的部分。

我计划有一个名为QuestionList 的组件,QuestionList 的目的是获取数据列表或获取问题列表,一旦获取,它将渲染几个QuestionDetail 组件。所以我会有一个QuestionList 和一个QuestionDetail

但同样,api 对每个问题都有一个类别,我想将该类别内容呈现为每个问题的标题。所以每次用户转到下一个问题时都会有不同的标题。

所以在上面的代码中,我没有让标题组件决定应该显示什么文本,而是稍微重构了它,以便应用程序组件决定在其中显示什么文本。

我是不是把我想要完成的事情搞砸了?我应该让标题组件决定应该显示什么文本吗?更重要的是如何让header 组件或App 组件呈现不同的类别?我是否应该创建一个单独的 CategoryList 组件,然后为每个呈现不同类别的特定组件创建一个 CategoryHeader 组件?

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    根据您的要求,您需要SectionList

    它已经支持renderSectionHeader,您可以在其中集成您的Header 组件

    一个例子是

    <SectionList 
      renderItem={({ item, index, section }) => <QuestionDetails {...item} />} // Render your Question Details Component here
      renderSectionHeader={({ section: { title } }) => <Header {...title}/>} //... Render your Custom Header Component here 
      sections={[ 
       { title: 'Category1', data: ['question1', 'question2'] }, 
       { title: 'Category2', data: ['question1', 'question2'] }, 
       { title: 'Category3', data: ['question1', 'question2'] }, 
       ]} 
      keyExtractor={(item, index) => item + index} />
    

    这只是一个示例,您可以根据此修改以生成适合您要求的数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 2021-08-25
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多