RN方法

✅ 1. 不带参数

📌 场景:点击文本时执行固定逻辑,不依赖传参。

const handlePress = () => {
  Alert.alert("提示", "你点击了文字!");
};

<Text onPress={handlePress}>点击我</Text>

✅ 2. 带一个参数

📌 场景:点击时传一个具体值,例如选项名称或 ID。

const handlePress = () => {
  Alert.alert("提示", "你点击了文字!");
};

<Text onPress={handlePress}>点击我</Text>

✅ 3. 带多个参数(推荐对象写法)

✅ 方法一:按顺序传多个值(不推荐)👇

const handlePress = (label, value, index) => {
  Alert.alert(`${label}:${value},索引:${index}`);
};

<Text onPress={() => handlePress("布局方向", "row", 2)}>点击传多个</Text>

✅ 方法二(推荐):传对象(带参数名)

const handlePress = ({ label, value, index }) => {
  Alert.alert("点击信息", `标签: ${label}\n值: ${value}\n索引: ${index}`);
};

<Text
  onPress={() =>
    handlePress({ label: "布局方向", value: "row", index: 2 })
  }
>
  点击传对象参数
</Text>

点击后返回值 改掉<text>的文本

✅ 实现步骤

  1. 用 useState 保存 <Text> 内容

  2. 点击时调用函数,并用返回值更新 Text 状态

import React, { useState } from "react";
import { Text, View, Alert } from "react-native";

// 外部方法:模拟返回值
const getNewText = (oldText) => {
  return oldText === "点击我" ? "已点击 ✅" : "点击我";
};

const ClickableText = () => {
  const [textValue, setTextValue] = useState("点击我");

  const handlePress = () => {
    const result = getNewText(textValue);  // 调用外部函数返回值
    setTextValue(result);                 // 更新 Text 内容
  };

  return (
    <View style={{ padding: 20 }}>
      <Text
        onPress={handlePress}
        style={{ fontSize: 18, color: "blue" }}
      >
        {textValue}
      </Text>
    </View>
  );
};

export default ClickableText;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容