react-native中的 event.target.value

IT技术 reactjs react-native
2021-05-20 17:45:40

我在 react-native 中有一个输入元素,它onChange绑定到handleClientInput. 我正在将动态数据分配给一个状态,它在网络上完美运行,但在 android 设备event.target.value上返回未定义:

const handleClientIDInput = (event) => {
    console.log("Input change");
    console.log(event.target.value); // logs undefined
    setClientID(event.target.value);
  };

这是我对功能组件的回报:

return (
    <SafeAreaView>
      <TextInput
        style={{
          borderWidth: 1,
          borderColor: "black",
        }}
        onChange={handleClientIDInput}
      />
      <Button title="Proceed" onPress={handleButtonClick} />
    </SafeAreaView>
  );

我使用的是 React Native 而不是 ReactJS,因为这在 ReactJS 上工作正常

3个回答

在 iOS 和 Android 中,你使用 React Native 和 ReactJS。这意味着您必须稍微调整 TextInput 组件,因为您无法从 event.target.value 访问文本。看看这个例子,这就是你可以让它工作的方法。

<TextInput
  style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
  onChangeText={text => console.log(text);
  value={value}
/>

当您为 iOS 或 Android 开发时,我建议您也查看 React Native 的文档,而不仅仅是 react 普通文档。

您可以使用 onChangeText={text => console.log(text); 这将起作用

如果您观察 React Native 的官方文档。它没有事件作为参数。它只是传递直接更改的文本。

https://reactnative.dev/docs/textinput#onchangetext

在您的“handleClientIDInput”中,它直接传递更改的文本而不是事件。只是信息 React 本机事件是本机事件。为了在 Web 和移动设备上兼容,您需要使用第三方 UI 框架,例如 Nativebase。我建议阅读 react-native 基础文档。Web 和 Mobile 在事件、路由等方面有所不同。