✅ 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>的文本
✅ 实现步骤
用 useState 保存 <Text> 内容
点击时调用函数,并用返回值更新 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;