【问题标题】:What's the type of TextInput target valueTextInput 目标值的类型是什么
【发布时间】:2019-08-27 06:58:42
【问题描述】:

如果使用以下代码库。

import React, { useState } from 'react';
import { TextInput } from 'react-native';

export function LoginInput() {
  const [text, setText] = useState('');

  function handlerTextChange(e) {
    setText(e.target.value)
  }

  return (
    <TextInput
      style={{ height: 40 }}
      value={text}
      onChangeText={handleTextChange}
    />
  )
}

如何定义 e 的类型,是事件类型还是任意类型?

【问题讨论】:

  • onChangeText 直接为您提供changed textonChangeText={(text) =&gt; handleTextChange(text)}.

标签: typescript react-native react-hooks


【解决方案1】:

在使用 onChange 时,您必须使用 e.target.value,其中 enative event e.target.value 是 string

仅使用 onChangeText 来获取文本,

<TextInput
    style={{height: 40, borderColor: 'gray', borderWidth: 1}}
    onChangeText={(text) => this.setState({text})}
    value={this.state.text}
/>

其中 text 只是字符串。

看看https://facebook.github.io/react-native/docs/textinput#onchange

【讨论】:

    【解决方案2】:

    将提供您输入的值。因此,类型是字符串值。

    import React, { Component } from 'react';
    import { View, StyleSheet, TextInput } from 'react-native';
    import { Constants } from 'expo';
    
    export default class App extends Component {
      state = {
        inputValue: '',
      };
    
      handlerTextChange = inputValue => {
        console.log(inputValue) // String you entered
        console.log(typeof inputValue) // string
        this.setState({ inputValue });
      };
    
      render() {
        return (
          <View style={styles.container}>
            <TextInput
              value={this.state.inputValue}
              onChangeText={this.handlerTextChange}
              style={{ width: 200, height: 44, padding: 8, borderWidth: 1, borderColor: '#ccc' }}
            />
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        paddingTop: Constants.statusBarHeight,
        backgroundColor: '#fff',
      },
    });
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-28
      • 2013-02-22
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 2019-12-06
      相关资源
      最近更新 更多