You need to enable JavaScript to run this app. React点击调整TextInput字号时输入内容被清空该如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

React点击调整TextInput字号时输入内容被清空该如何解决?

问题原因
  • 你使用的是React Native的TextInput组件,它的事件回调结构和Web端原生input不同,现有代码中onChange回调通过e.target.value无法正确获取输入内容,导致父组件存储的value实际为undefined。当你点击调整字号触发MyInput组件重渲染时,输入框绑定的value为undefined,就会出现内容被清空的异常。
解决方案

两种修改方式二选一即可:

方案1:调整onChange的取值逻辑

从onChange返回的事件对象的nativeEvent中取输入文本:

const MyInput = React.forwardRef((props,ref) => {
  const [fontSize, setFontSize] = useState(12);
  React.useImperativeHandle(ref,() => ({
    incFont: () => {
      setFontSize(fontSize => fontSize+2);
    },
    decFont: () => {
      setFontSize(fontSize => fontSize-2);
    }
  }))
  return(
    <TextInput
      value={props.value}
      onChange={(e) => props.setValue(e.nativeEvent.text)}
      style={{ fontSize, borderColor: "red", borderWidth: 1 }}
    />
  )
})

方案2:使用官方推荐的onChangeText回调(更简洁)

TextInput内置了onChangeText回调,会直接返回当前输入的文本内容,无需手动解析事件对象:

const MyInput = React.forwardRef((props,ref) => {
  const [fontSize, setFontSize] = useState(12);
  React.useImperativeHandle(ref,() => ({
    incFont: () => {
      setFontSize(fontSize => fontSize+2);
    },
    decFont: () => {
      setFontSize(fontSize => fontSize-2);
    }
  }))
  return(
    <TextInput
      value={props.value}
      onChangeText={(text) => props.setValue(text)}
      style={{ fontSize, borderColor: "red", borderWidth: 1 }}
    />
  )
})

修改完成后调整字号时,输入框绑定的value为父组件正确存储的输入内容,不会再被清空。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 11:03:04