javascript - 无法在 native react 中读取 null 的属性字符串

标签 javascript reactjs react-native

我总是得到这个错误

Cannot read property 'todoText' of null in react native

用于提交表单。我正在尝试创建一个将提交值的表单。

import * as React from "react";
import { View, Text, StyleSheet, TextInput, TouchableOpacity } from 'react-native';

interface TodoState{
    todoText?: string;
}
interface TodoProps{
    text: string;
}
export default class AddTodo extends React.Component <TodoProps,TodoState> {

    constructor(props:TodoProps){
        super(props);
        this.setState({todoText:" "});
    }

    handleSubmit = () => {
        console.log(this.state.todoText);
    }

    updateText = (text) => {
        this.setState((state) => {
            return { todoText: text };
        });
    };

    render() {
        return (
            <View style={{margin: 128, marginLeft: 15, marginRight:15}}>
                <TextInput style={styles.input} placeholder='Todo' onChangeText={(text) => this.setState({todoText:text})} value={this.state.todoText} />
                <TouchableOpacity onPress={this.handleSubmit.bind(this)}>
                    <Text style={styles.button}>Submit</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

我试图遵循这个 link但我总是得到那个错误。正如我在 react 中所理解的那样,它按照我绑定(bind)函数的方式工作。我不知道 react-native 是否有其他方法可以做到这一点。我已经遵循了它的文档。我错过了我的代码吗?但是,如果您有教程将进行表单验证。深入研究 React Native 将是一件很棒的事情。我是这项技术的新手。

最佳答案

关于你的第一次渲染,它找不到todoText。因为 constructor 中的 initial 是错误的。将 constructor 更改为:

constructor(props:TodoProps){
    super(props);
    this.state = {
      todoText:" "
    };
}

关于javascript - 无法在 native react 中读取 null 的属性字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43886480/

相关文章:

javascript - 获取数据然后渲染到 dom React

javascript - 仅在单击时分派(dispatch)到 Prop

css - 如何在带有 borderRadius 的 View 组件中放置两个 View 组件?

Javascript 未定义错误但控制台日志显示值

javascript - 最基本的 Angular 应用程序无法运行

javascript - TS2403 : Subsequent variable declarations must have the same type in react

javascript - 在react-native中找不到变量itemData

javascript - bxslider 稍微切断图像

javascript - 如何在reactjs中根据日期降序对对象数组进行排序?

javascript - React Native setState 不是函数