You need to enable JavaScript to run this app. React Native如何实现跨组件传值至TextInput且仍可编辑内容
优惠活动
大模型
产品
解决方案
定价
更多

React Native如何实现跨组件传值至TextInput且仍可编辑内容

问题原因

你的代码有两个核心错误导致输入框无法编辑:

  • TextInput的value属性绑定了路由参数传递过来的固定值title、description,这两个值是从上层组件传过来的常量,不会随着输入动作变化,每次组件重渲染都会用这个固定值覆盖输入框内容。
  • 状态初始化逻辑不符合编辑页需求,当前state里的title、description初始值是空字符串,没有默认填充传入的待编辑内容。

修复方案

调整状态初始化逻辑,同时修改TextInput的value绑定对象为你维护的state变量即可,修复后的完整代码如下:

export default function EditTodoScreen({ route }) {
  const { title, description } = route.params
  // 修正初始值,把传入的待编辑内容作为state的初始值
  const [state, setState] = useState({ title, description });

  const {isLoading, mutateAsync} = useUpdateTodo()

  const handleSubmitUpdatedTodo = async () => {
    try {
      const response = await mutateAsync(state)
      showToast(response.data.message);
    } catch (error) {
      showToast(error);
    }
  };

  return (
    <View style={styles.container}>
      <View>
        <Text style={styles.inputHeader}>Title</Text>
        <TextInput
          placeholder="Please enter title"
          style={styles.input}
          allowFontScaling
          onChangeText={(title) => {
            setState({ ...state, title });
            console.log(title)
          }}
          {/* value绑定state里的title,而非路由参数的固定值 */}
          value={state.title}
        />
        <Text style={styles.inputHeader}>Description</Text>
        <TextInput
          placeholder="Please enter description"
          style={styles.input}
          onChangeText={(description) => {
            setState({ ...state, description });
          }}
          {/* value绑定state里的description,而非路由参数的固定值 */}
          value={state.description}
        />
      </View>
      <Button
        buttonStyle={styles.button}
        title="submit"
        onPress={handleSubmitUpdatedTodo}
      />
      {isLoading ? <ActivityIndicator color="red" /> : null}
    </View>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 00:45:04