【问题标题】:How to pass array of View/Component in react native?如何在本机反应中传递视图/组件数组?
【发布时间】:2017-01-07 03:46:40
【问题描述】:

我正在用 React Native 制作 App 框架。框架由一些基本屏幕组成,如登录屏幕、选项卡屏幕。该框架的目的是为将从头开始开发的新应用程序提供基本设计。

标签屏幕

我们知道每个选项卡都会有单独的视图来显示。我想让 tabscreen 完全可定制。这意味着基于传递的视图列表和选项卡列表,它应该呈现。

为此,我需要将视图/组件数组作为道具传递给 TabScreen。

  1. 如何制作视图/组件数组?
  2. 如何将数组作为道具传递给 TabScreen?

下面是TabScreen的代码

'uses strict'

import {StyleSheet, View, Text, Image} from 'react-native';
import React, {Component, PropTypes} from 'react';
import {IndicatorViewPager, PagerTabIndicator} from 'rn-viewpager';

export default class TabScreen extends Component {
  
  constructor (props) {
    super(props)
  }
  
  static propTypes = {
    views : PropTypes.arrayOf(PropTypes.instanceOf(View)).isRequired,
    tabs: PropTypes.arrayOf(PropTypes.shape({
      text: PropTypes.string,
      iconSource: Image.propTypes.source,
      selectedIconSource: Image.propTypes.source
    })).isRequired,
  }
  render() {
    
    return (
      <View style={{flex:1}}>
      <IndicatorViewPager
      style={{flex:1, paddingTop:20, backgroundColor:'white'}}
      indicator={<PagerTabIndicator tabs={this.props.tabs} />}>
      {views}
      </IndicatorViewPager>
      </View>
    );
  }
}
module.exports = TabScreen;

请帮忙

【问题讨论】:

    标签: android react-native android-viewpager react-native-android


    【解决方案1】:

    你不需要传递react native组件的数组,你必须使用组件的children,像这样:

    在你的上层组件的render方法中:

    <TabScreen>
        <View><Text>First tab</Text>
        <View><Text>Second tab</Text></View>
        {/* And so on... */}
    </TabScreen>
    

    然后,在您的 TabScreen 组件中,执行以下操作:

    render() {
    
        return (
          <View style={{flex:1}}>
          <IndicatorViewPager
          style={{flex:1, paddingTop:20, backgroundColor:'white'}}
          indicator={<PagerTabIndicator tabs={this.props.tabs} />}>
          {this.props.children}
          </IndicatorViewPager>
          </View>
        );
      }
    

    无论如何,回答您的问题:

    如何制作视图/组件数组?

    就像任何其他数组一样。例如,map:

    let elements = ['First Tab', 'Second Tab'].map((text)=> <View><Text>{text}</Text></View>))
    

    如何将数组作为道具传递给 TabScreen?

    在 props 方面,数组与任何其他数据类型没有什么不同(任何变量都可以作为 prop 传递,除非它具有某种验证机制,在这种情况下会引发警告)。

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      相关资源
      最近更新 更多