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

React Native:TouchableHighlight点击后State未即时正确更新问题

TouchableHighlight点击后State更新异常问题

点击TouchableHighlight组件后,State不会立即更新,只有点击另一个已渲染组件后才会触发更新,且追加的是上一次点击的字母。

相关代码

export default function App() {
  const [word, setword] = useState('');
  const handleChange=(e) => {
    setword(word.concat(e.target.outerText));
  };

  return (
    <View style={styles.container}>
      <View style={styles.row}>
      {wordpuzzle.square[0].map((letter, index) => {
        return(
          <TouchableHighlight style={styles.touchableHighlight} key={index} onPress={handleChange}>
            <View style={styles.button}>
              <Text style={styles.text}>{letter}</Text>
            </View>
          </TouchableHighlight>
        )})
      } 
    </View>
  </View>
  );
}

数据来源wordpuzzle.json

{
    "square": [
        ["P", "E", "R", "E"],
        ["I", "U", "B", "A"],
        ["T", "A", "B", "L"],
        ["E", "H", "C", "I"]
    ],
    "10": ["pubblicati"],
    "9": ["pubbliche", "pubblicai"],
    "8": ["pubblica"],
    "7": ["pubiche", "barbuta", "barbuti", "barbute"],
    "6": ["pubica", "rubati", "rubate"],
    "5": ["barbe", "beare"],
    "4": ["pere", "pera", "erba", "bali", "pube", "pubi", "bare",
        "taci", "aura", "aure", "ruba"
    ],
    "3": ["eta", "pia", "pie", "che", "ali", "bea"]
}

问题原因及解决方法

  • React Native事件不兼容DOM属性:e.target.outerText是Web端的写法,React Native的onPress事件参数不是DOM事件,无法通过这种方式获取点击的字母,这会导致获取的值错误或为空。
  • State异步更新的旧值依赖:直接使用word.concat()更新State时,word是组件上一次渲染时的快照,因为useState的更新是异步的,无法保证拿到最新的State值,从而导致更新延迟,出现追加旧字母的情况。

修改后的代码

export default function App() {
  const [word, setword] = useState('');

  // 接收点击的字母作为参数
  const handleChange = (letter) => {
    // 函数式更新,基于最新的State值修改
    setword(prevWord => prevWord.concat(letter));
  };

  return (
    <View style={styles.container}>
      <View style={styles.row}>
        {wordpuzzle.square[0].map((letter, index) => (
          <TouchableHighlight 
            style={styles.touchableHighlight} 
            key={index} 
            // 点击时直接传递当前字母
            onPress={() => handleChange(letter)}
          >
            <View style={styles.button}>
              <Text style={styles.text}>{letter}</Text>
            </View>
          </TouchableHighlight>
        ))}
      </View>
    </View>
  );
}

修改后,点击每个按钮时会直接把对应的字母传给handleChange,同时通过函数式更新State,确保每次都基于最新的State值追加字母,解决更新延迟和值错误的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:23:09