event.target.value 输入更改时未定义

event.target.value undefined on input change

我终于到了想不通的地步了。我的目标很简单。我在 React Native 组件中有一个输入字段。

我想将输入文本的值保存到redux状态(稍后)。但是,我总是在 e.target.value 上得到 undefined。这个问题已经发布了数百万次,我尝试了很多解决方案。 None 他们成功了。我想我还漏掉了其他东西。

顺便说一句。该按钮仅用于获取日志中的最新状态。

这是我的组件:

import React, {
  Component
} from 'react';
import {
  Button,
  StyleSheet,
  TextInput,
  View
} from 'react-native';
import allActions from '../../actions/allActions';
import {
  useDispatch,
  useSelector
} from 'react-redux';
import store from '../../store';

const styles = StyleSheet.create({
  input: {
    height: 40,
    marginTop: 20,
    borderWidth: 1,
    borderColor: '#d3d3d3',
    padding: 10,
  }
});


class Name extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user: ""
    };

    this.handleChange = this.handleChange.bind(this);
    this.getMyState = this.getMyState.bind(this);
  }

  handleChange(event) {
    event.preventDefault();
    this.setState({
      user: event.target.value
    });
  }

  getMyState(event) {
    event.preventDefault();
    console.log(this.state.user);
  }
  render() {

    return ( <
      View >
      <
      TextInput style = {
        styles.input
      }
      onChange = {
        this.handleChange
      }
      /> <
      Button title = {
        'get log'
      }
      onPress = {
        this.getMyState
      }
      /> <
      /View>
    );
  }
}

export default Name;

像这样使用 onChangeText 而不是 onChange:

const myInputFunction(text: string) {
  if (/* check whatever you want */) {
    this.setState({inputText: text})
  }
}

<TextInput
  value={this.state.inputText}
  maxLength={1}
  onSubmitEditing={this.textHandler}
  onChangeText={(text) => myInputFunction(text)} // Not sure if you have to write this.function here I am using React State hooks and functional components instead of classes
/>
´´´

对于任何为此苦苦挣扎的人,这是我想出的解决方案。感谢@Maximilian Dietel,我使用 onChange 而不是 onChangeText 意识到了我最初的问题。之后,我将 class 组件更改为功能组件,以便我可以使用我的钩子将新状态保存到 redux。

import React, {Component} from 'react';
import {Button, StyleSheet, Text, TextInput, View} from 'react-native';
import allActions from '../../actions/allActions';
import {useDispatch, useSelector} from 'react-redux';
import store from '../../store';

const styles = StyleSheet.create({
    input: {
        height: 40,
        marginTop: 20,
        borderWidth: 1,
        borderColor: '#d3d3d3',
        padding: 10,
    }
});

function Name (props) {
    const dispatch = useDispatch();

    /**
     * Save the new user to the state
     * @param text
     */
    const handleChange = (text) => {
        dispatch(allActions.userActions.setUser(text));
    }
        return (
            <View>
                <TextInput
                    style={styles.input}
                    defaultValue={store.getState().user.user}
                    onChangeText={handleChange}
                />
            </View>
        );
}

export default Name;