首页 > 解决方案 > 如何在没有状态的情况下实现 TextInput [React-native]

问题描述

我正在开发一个用户将不断输入大量记录的应用程序。应用程序功能已完成,但在低端手机中性能有点慢。由于我是新手,所以我对此并不了解。但是当我用谷歌搜索这个问题时,已经注意到当状态发生变化时,整个应用程序都会重新渲染。因此,为了减少状态更改,我想知道如何在不使用 state 的情况下使用 TextInput 。因为在我的 TextInputonChangeText中,每次按键都会更新状态。

这是项目Demo的演示点心

  <View style={styles.fixedform}>
    <View style={styles.textinputViewleft}>
        <TextInput 
        style={styles.textinput} 
        ref={firstref}
        label="Digit"
        returnKeyType="next"
        value={digit.value}
        onChangeText={(text) => { setDigit({ value: text, error: '' }); if (text.length === 3) { ref.current.focus(); } }}
        error={!!digit.error}
        errorText={digit.error}
        keyboardType="numeric"
        maxLength={3}
        minLength={3}/>
    </View>
    <View style={styles.textinputView}>
        <TextInput 
        style={styles.textinput} 
        ref={ref}
        label="Count"
        value={count.value}
        onChangeText={(text) => setCount({ value: text, error: '' })}
        error={!!count.error}
        errorText={count.error}
        keyboardType="numeric"
        maxLength={3}/>
    </View>
    <View style={styles.textinputView}>
        <Button loading={loading} disabled={disabled} style={styles.buttonView} mode="contained" onPress={onSubmitPress}>Submit</Button>
    </View>
  </View>

标签: reactjsreact-native

解决方案


Try this way, It will not rerender on text change and hold the value on key press like

<TextInput 
        ...
        value={digit.value} // remove this 
        onChangeText={(text) => digit.value = text };
        ...
/>

To clear value, try one of this

1- firstref.current.clear();
2- firstref.current.setNativeProps({ text: '' });
3- firstref.current.value = '';

推荐阅读