React Native基础组件 #

概述 #

React Native 提供了一套核心组件,这些组件映射到对应平台的原生 UI 组件。本章节介绍最常用的基础组件。

View #

View 是最基础的容器组件,类似于 Web 开发中的 div。

基本用法 #

tsx
import React from 'react';
import {View, StyleSheet} from 'react-native';

const ViewExample = () => {
  return (
    <View style={styles.container}>
      <View style={styles.box1} />
      <View style={styles.box2} />
      <View style={styles.box3} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  box1: {
    width: 100,
    height: 100,
    backgroundColor: '#FF6B6B',
    marginBottom: 10,
  },
  box2: {
    width: 100,
    height: 100,
    backgroundColor: '#4ECDC4',
    marginBottom: 10,
  },
  box3: {
    width: 100,
    height: 100,
    backgroundColor: '#45B7D1',
  },
});

export default ViewExample;

常用属性 #

属性 类型 说明
style object 样式对象
onLayout function 布局变化回调
pointerEvents string 触摸事件处理方式
hitSlop object 扩大触摸区域
collapsable boolean 是否可折叠优化

onLayout 获取尺寸 #

tsx
const LayoutExample = () => {
  const [size, setSize] = useState({width: 0, height: 0});

  return (
    <View
      style={styles.container}
      onLayout={event => {
        const {width, height} = event.nativeEvent.layout;
        setSize({width, height});
      }}>
      <Text>Width: {size.width}</Text>
      <Text>Height: {size.height}</Text>
    </View>
  );
};

Text #

Text 组件用于显示文本内容。

基本用法 #

tsx
import React from 'react';
import {Text, StyleSheet} from 'react-native';

const TextExample = () => {
  return (
    <Text style={styles.text}>
      Hello, React Native!
    </Text>
  );
};

const styles = StyleSheet.create({
  text: {
    fontSize: 18,
    color: '#333',
    textAlign: 'center',
  },
});

export default TextExample;

嵌套文本 #

Text 可以嵌套,内部 Text 会继承外部样式:

tsx
const NestedText = () => {
  return (
    <Text style={styles.paragraph}>
      这是普通文本,
      <Text style={styles.bold}>这是粗体文本</Text>
      ,
      <Text style={styles.highlight}>这是高亮文本</Text>
      。
    </Text>
  );
};

const styles = StyleSheet.create({
  paragraph: {
    fontSize: 16,
    color: '#333',
    lineHeight: 24,
  },
  bold: {
    fontWeight: 'bold',
  },
  highlight: {
    color: '#007AFF',
  },
});

常用属性 #

属性 类型 说明
numberOfLines number 最大显示行数
ellipsizeMode string 省略号位置 (head/middle/tail/clip)
onPress function 点击事件
selectable boolean 是否可选择
adjustsFontSizeToFit boolean 自动调整字体大小
allowFontScaling boolean 是否响应系统字体缩放

文本截断 #

tsx
const TruncatedText = () => {
  return (
    <View style={styles.container}>
      <Text numberOfLines={1} ellipsizeMode="tail" style={styles.text}>
        这是一段很长的文本,会被截断显示省略号
      </Text>
      <Text numberOfLines={2} style={styles.text}>
        这是一段很长的文本,最多显示两行,超出部分会被截断显示省略号
      </Text>
    </View>
  );
};

Image #

Image 组件用于显示图片。

加载网络图片 #

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

const NetworkImage = () => {
  return (
    <Image
      source={{uri: 'https://example.com/image.jpg'}}
      style={styles.image}
      resizeMode="cover"
    />
  );
};

const styles = StyleSheet.create({
  image: {
    width: 200,
    height: 200,
    borderRadius: 10,
  },
});

export default NetworkImage;

加载本地图片 #

tsx
const LocalImage = () => {
  return (
    <Image
      source={require('./assets/logo.png')}
      style={styles.image}
    />
  );
};

常用属性 #

属性 类型 说明
source object/number 图片源
resizeMode string 缩放模式 (cover/contain/stretch/repeat/center)
blurRadius number 模糊半径
defaultSource number 占位图
onLoad function 加载完成回调
onError function 加载失败回调

resizeMode 效果 #

tsx
const ResizeModeExample = () => {
  const modes = ['cover', 'contain', 'stretch', 'repeat', 'center'] as const;
  const uri = 'https://example.com/image.jpg';

  return (
    <ScrollView>
      {modes.map(mode => (
        <View key={mode} style={styles.item}>
          <Text>{mode}</Text>
          <Image
            source={{uri}}
            style={styles.image}
            resizeMode={mode}
          />
        </View>
      ))}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  item: {
    marginBottom: 20,
    alignItems: 'center',
  },
  image: {
    width: 150,
    height: 150,
    backgroundColor: '#f0f0f0',
  },
});

图片加载状态 #

tsx
const ImageWithLoading = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  return (
    <View>
      {loading && <ActivityIndicator />}
      {error && <Text>加载失败</Text>}
      <Image
        source={{uri: 'https://example.com/image.jpg'}}
        style={styles.image}
        onLoadStart={() => setLoading(true)}
        onLoadEnd={() => setLoading(false)}
        onLoad={() => {
          setLoading(false);
          setError(false);
        }}
        onError={() => {
          setLoading(false);
          setError(true);
        }}
      />
    </View>
  );
};

ScrollView #

ScrollView 是一个可滚动的容器组件。

基本用法 #

tsx
import React from 'react';
import {ScrollView, View, Text, StyleSheet} from 'react-native';

const ScrollViewExample = () => {
  return (
    <ScrollView style={styles.container}>
      {Array.from({length: 20}).map((_, index) => (
        <View key={index} style={styles.item}>
          <Text style={styles.text}>Item {index + 1}</Text>
        </View>
      ))}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  item: {
    height: 80,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    marginHorizontal: 16,
    marginVertical: 8,
    borderRadius: 8,
  },
  text: {
    fontSize: 18,
    color: '#333',
  },
});

export default ScrollViewExample;

常用属性 #

属性 类型 说明
horizontal boolean 是否水平滚动
showsVerticalScrollIndicator boolean 显示垂直滚动条
showsHorizontalScrollIndicator boolean 显示水平滚动条
pagingEnabled boolean 分页滚动
scrollEnabled boolean 是否可滚动
bounces boolean iOS 弹性效果
onScroll function 滚动事件
onMomentumScrollEnd function 滚动结束回调
ref RefObject 获取滚动实例

滚动到指定位置 #

tsx
const ScrollToExample = () => {
  const scrollViewRef = useRef<ScrollView>(null);

  const scrollToTop = () => {
    scrollViewRef.current?.scrollTo({y: 0, animated: true});
  };

  const scrollToBottom = () => {
    scrollViewRef.current?.scrollToEnd({animated: true});
  };

  return (
    <View style={styles.container}>
      <ScrollView ref={scrollViewRef} style={styles.scrollView}>
        {/* 内容 */}
      </ScrollView>
      <View style={styles.buttons}>
        <Button title="顶部" onPress={scrollToTop} />
        <Button title="底部" onPress={scrollToBottom} />
      </View>
    </View>
  );
};

下拉刷新 #

tsx
const RefreshControlExample = () => {
  const [refreshing, setRefreshing] = useState(false);
  const [data, setData] = useState<string[]>([]);

  const onRefresh = async () => {
    setRefreshing(true);
    const newData = await fetchData();
    setData(newData);
    setRefreshing(false);
  };

  return (
    <ScrollView
      refreshControl={
        <RefreshControl
          refreshing={refreshing}
          onRefresh={onRefresh}
          colors={['#007AFF']}
          tintColor="#007AFF"
        />
      }>
      {data.map(item => (
        <Text key={item}>{item}</Text>
      ))}
    </ScrollView>
  );
};

TouchableOpacity #

TouchableOpacity 是可触摸的透明度反馈组件。

基本用法 #

tsx
import React from 'react';
import {TouchableOpacity, Text, StyleSheet} from 'react-native';

const ButtonExample = () => {
  const handlePress = () => {
    console.log('Button pressed');
  };

  return (
    <TouchableOpacity style={styles.button} onPress={handlePress}>
      <Text style={styles.text}>Click Me</Text>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 8,
    alignItems: 'center',
  },
  text: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
});

export default ButtonExample;

触摸反馈组件对比 #

组件 效果 适用场景
TouchableOpacity 透明度变化 通用按钮
TouchableHighlight 背景变暗 需要明确反馈
TouchableNativeFeedback 水波纹效果 Android 原生风格
TouchableWithoutFeedback 无反馈 隐藏键盘等

TouchableNativeFeedback(Android) #

tsx
const NativeButton = () => {
  return (
    <TouchableNativeFeedback
      onPress={handlePress}
      background={TouchableNativeFeedback.Ripple('#007AFF', false)}>
      <View style={styles.button}>
        <Text style={styles.text}>Native Button</Text>
      </View>
    </TouchableNativeFeedback>
  );
};

禁用状态 #

tsx
const DisabledButton = () => {
  const [disabled, setDisabled] = useState(false);

  return (
    <TouchableOpacity
      style={[styles.button, disabled && styles.disabled]}
      onPress={handlePress}
      disabled={disabled}>
      <Text style={styles.text}>
        {disabled ? 'Loading...' : 'Submit'}
      </Text>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#007AFF',
    padding: 12,
    borderRadius: 8,
  },
  disabled: {
    backgroundColor: '#ccc',
  },
  text: {
    color: '#fff',
    fontSize: 16,
  },
});

TextInput #

TextInput 是文本输入组件。

基本用法 #

tsx
import React, {useState} from 'react';
import {TextInput, View, StyleSheet} from 'react-native';

const InputExample = () => {
  const [value, setValue] = useState('');

  return (
    <TextInput
      style={styles.input}
      value={value}
      onChangeText={setValue}
      placeholder="请输入内容"
      placeholderTextColor="#999"
    />
  );
};

const styles = StyleSheet.create({
  input: {
    height: 48,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    paddingHorizontal: 16,
    fontSize: 16,
  },
});

export default InputExample;

常用属性 #

属性 类型 说明
value string 输入值
onChangeText function 文本变化回调
placeholder string 占位文本
secureTextEntry boolean 密码输入
keyboardType string 键盘类型
multiline boolean 多行输入
maxLength number 最大长度
editable boolean 是否可编辑
returnKeyType string 回车键类型
onSubmitEditing function 提交回调

键盘类型 #

tsx
const KeyboardTypes = () => {
  return (
    <View>
      <TextInput
        placeholder="默认键盘"
        keyboardType="default"
      />
      <TextInput
        placeholder="数字键盘"
        keyboardType="numeric"
      />
      <TextInput
        placeholder="邮箱键盘"
        keyboardType="email-address"
      />
      <TextInput
        placeholder="电话键盘"
        keyboardType="phone-pad"
      />
    </View>
  );
};

表单示例 #

tsx
const LoginForm = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const passwordRef = useRef<TextInput>(null);

  const handleSubmit = () => {
    console.log({email, password});
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        value={email}
        onChangeText={setEmail}
        placeholder="邮箱"
        keyboardType="email-address"
        autoCapitalize="none"
        returnKeyType="next"
        onSubmitEditing={() => passwordRef.current?.focus()}
      />
      <TextInput
        ref={passwordRef}
        style={styles.input}
        value={password}
        onChangeText={setPassword}
        placeholder="密码"
        secureTextEntry
        returnKeyType="done"
        onSubmitEditing={handleSubmit}
      />
      <TouchableOpacity style={styles.button} onPress={handleSubmit}>
        <Text style={styles.buttonText}>登录</Text>
      </TouchableOpacity>
    </View>
  );
};

其他常用组件 #

ActivityIndicator #

加载指示器:

tsx
const LoadingExample = () => {
  return (
    <View style={styles.container}>
      <ActivityIndicator size="large" color="#007AFF" />
      <ActivityIndicator size="small" color="#999" />
    </View>
  );
};

Switch #

开关组件:

tsx
const SwitchExample = () => {
  const [isEnabled, setIsEnabled] = useState(false);

  return (
    <Switch
      value={isEnabled}
      onValueChange={setIsEnabled}
      trackColor={{false: '#767577', true: '#81b0ff'}}
      thumbColor={isEnabled ? '#007AFF' : '#f4f3f4'}
    />
  );
};

SafeAreaView #

安全区域视图,适配刘海屏:

tsx
const SafeAreaExample = () => {
  return (
    <SafeAreaView style={styles.container}>
      <Text>内容在安全区域内</Text>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
});

总结 #

本章节介绍了 React Native 的核心基础组件:

  • View:基础容器组件
  • Text:文本显示组件
  • Image:图片显示组件
  • ScrollView:滚动容器组件
  • TouchableOpacity:触摸反馈组件
  • TextInput:文本输入组件

这些组件是构建 React Native 应用的基础,掌握它们的使用方法非常重要。

继续学习 样式系统,了解如何为组件添加样式。

最后更新:2026-03-28