使用打字稿将 React Native 中的 UseState 传递给输入框组件并在更改时更新它

问题描述

我在将使用状态传递给自定义文本输入组件时遇到了一些问题。我想在每次用户在输入框中进行更改时更新符号的状态。使用状态符号不会更新并返回为未定义。

App.tsx

    const App = () => {
    
    const [symbol,setSymbol] = useState('AMD');
    
    
       function handleSymbolChange() {
        setSymbol(symbol);
      }
    
    return (
    <View>
      <AppTextInput placeholder="Symbol" icon="activity" value={symbol} 
      onTextInputChange= {handleSymbolChange}/>
    </View>
  );
};
    }

AppTextInput.tsx

 interface Props {
      icon: string;
      placeholder: string;
      value: string;
      onTextInputChange: any;

}

    const AppTextInput: React.FC<Props> = ({
      icon,placeholder,value,onTextInputChange,}) => {
     
       const handleChange = (e: any) => {
        onTextInputChange(e.target.value);
        console.log(e.target.value);
      };
    
      return (
        <View>
            <Icon name={icon} size={20}/>
     
          <TextInput
            style={styles.textInput}
            placeholder={placeholder}
            value={value}
            onChange={handleChange}
          />
        </View>
      );
    };

解决方法

您的代码未按预期运行的原因有两个。

第一个原因是 onTextInputChange 传回一个值 e.target.value,但您没有在 handleSymbolChange 回调中使用该值。您可能应该将 handleSymbolChange 函数更改为如下所示:

function handleSymbolChange(value: string) {
  setSymbol(value);
}

第二个原因是您没有正确使用 e onChange 回调的 TextInput 参数。如果您查看文档,您将看到 onChange 回调需要具有以下属性的对象:{ nativeEvent: { eventCount,target,text} } 作为参数,而您使用的是 e.target.value。为了让它工作,你需要把它改成这样:

import {
  NativeSyntheticEvent,TextInput,TextInputChangeEventData,View,} from 'react-native';

const App = () => {
  const handleChange = ({
    nativeEvent: { text },}: NativeSyntheticEvent<TextInputChangeEventData>) => {
    onTextInputChange(text);
  };

  return (
    <View>
      <TextInput onChange={handleChange} />
    </View>
  );
};

或者改用 onChangeText 属性:

import { TextInput,View } from 'react-native';

const App = () => {
  const handleChange = (text: string) => {
    onTextInputChange(text);
  };

  return (
    <View>
      <TextInput onChangeText={handleChange} />
    </View>
  );
};