首页 > 解决方案 > 如何在本机反应中将无状态函数转换为类组件

问题描述

我是 react native 的新手,我一直在寻找如何将此函数转换为 react native 中的类组件。请我需要帮助将下面的代码转换为反应组件。

import React from 'react';
import { View, Image, ScrollView } from 'react-native';

import styles from './styles';

export default ({captures=[]}) => (
    <ScrollView 
        horizontal={true}
        style={[styles.bottomToolbar, styles.galleryContainer]} 
    >
        {captures.map(({ uri }) => (
            <View style={styles.galleryImageContainer} key={uri}>
                <Image source={{ uri }} style={styles.galleryImage} />
            </View>
        ))}
    </ScrollView>
);

标签: javascriptreact-nativereact-native-component

解决方案


要将其转换为类组件,只需将代码移动到类组件的 render 方法中,并将对 的引用更改为props对 的引用this.props。对于此组件,无需进行其他更改。

export default class Example extends React.Component {
  render () {
    const { captures = [] } = this.props;
    return (
      <ScrollView 
        horizontal={true}
        style={[styles.bottomToolbar, styles.galleryContainer]} 
      >
        {captures.map(({ uri }) => (
          <View style={styles.galleryImageContainer} key={uri}>
            <Image source={{ uri }} style={styles.galleryImage} />
          </View>
        ))}
      </ScrollView>
    )
  }
}

推荐阅读