You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Expo React Native中,如何点击父容器唤起TextInput编辑状态?

解决方案

当然可行,你只需要给TextInput添加一个ref,然后在TouchableOpacity的onPress事件里调用输入框的focus()方法,就能让它进入编辑状态。

具体修改代码如下:

import { useRef } from 'react';
import { TouchableOpacity, View, Text, TextInput } from 'react-native';

// 你的组件内部逻辑
const inputRef = useRef(null);

return (
  <TouchableOpacity onPress={() => inputRef.current?.focus()}>
    <View style={styles.container}>
      <Text> Protein</Text>
      <TextInput
        ref={inputRef} // 绑定引用到输入框
        style={styles.input}
        onChangeText={(event) => setItem(prevState => ({ ...prevState, proteins: parseInt(event) }))}
        keyboardType={'numeric'}
        value={item.proteins?.toString()} // 注意:数字类型值要转成字符串,避免TextInput警告
        placeholder='0'
      />
    </View>
  </TouchableOpacity>
);
  • 用useRef创建引用对象inputRef,关联到目标TextInput上
  • 在TouchableOpacity的点击事件中,调用inputRef.current?.focus()触发输入框聚焦,可选链?.是为了避免组件未挂载时的报错
  • 额外提示:TextInput的value必须是字符串类型,如果item.proteins是数字,记得转成字符串格式

内容的提问来源于stack exchange,提问作者benwl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:35:20