React Native自定义TextInput组件onChangeText失效问题求助
React Native自定义TextInput组件onChangeText失效问题
我在React Native中创建了CustomTextInput组件,但组件的onChangeText属性无法正常工作,原生TextInput却能正常运行。代码如下:
import React, { useState } from 'react'; import { View, StyleSheet } from 'react-native'; import { TextInput } from 'react-native'; const App = () => { const [inputValue, setInputValue] = useState(''); const CustomTextInput = ({ value, onChangeText, placeholder, style }) => { return ( <TextInput value={value} onChangeText={onChangeText} placeholder={placeholder} style={style} /> ); }; const handleTextChange = (text) => { setInputValue(text); }; return ( <View style={styles.container}> <CustomTextInput value={inputValue} onChangeText={handleTextChange} placeholder="Custom, not working..." style={styles.textInput} /> <TextInput value={inputValue} onChangeText={handleTextChange} placeholder="Working.." style={styles.textInput} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#f0f0f0', }, textInput: { width: '80%', height: 40, borderWidth: 1, borderColor: 'gray', padding: 10, }, }); export default App;
问题原因
CustomTextInput被定义在App组件的函数内部。每次App组件因状态更新(比如inputValue变化)重新渲染时,CustomTextInput都会被重新创建为一个全新的组件类型,这会导致React无法正确维护组件的状态和回调关联,最终使得onChangeText无法触发。
解决方案
将CustomTextInput组件移到App组件外部定义,确保它只被创建一次。
修改后的代码如下:
import React, { useState } from 'react'; import { View, StyleSheet, TextInput } from 'react-native'; // 将CustomTextInput移到App组件外部 const CustomTextInput = ({ value, onChangeText, placeholder, style }) => { return ( <TextInput value={value} onChangeText={onChangeText} placeholder={placeholder} style={style} /> ); }; const App = () => { const [inputValue, setInputValue] = useState(''); const handleTextChange = (text) => { setInputValue(text); }; return ( <View style={styles.container}> <CustomTextInput value={inputValue} onChangeText={handleTextChange} placeholder="Custom, now working..." style={styles.textInput} /> <TextInput value={inputValue} onChangeText={handleTextChange} placeholder="Working.." style={styles.textInput} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#f0f0f0', }, textInput: { width: '80%', height: 40, borderWidth: 1, borderColor: 'gray', padding: 10, }, }); export default App;
修改后,CustomTextInput作为稳定的组件类型,React能正确绑定回调函数,onChangeText会正常触发,输入值也会同步更新。
内容的提问来源于stack exchange,提问作者Cem Yeten
相关产品推荐
相关产品推荐

