【问题标题】:React Native Firebase state undefinedReact Native Firebase 状态未定义
【发布时间】:2020-06-25 19:32:03
【问题描述】:

我已经尝试了多种实现,但我似乎无法让状态不是未定义的。我试过箭头函数,我试过在 onChange 事件中绑定它,但似乎没有任何效果。有人可以拿我的代码库给我一些关于我做错了什么的见解吗?谢谢!

import React from 'react';
import {View, Image, StyleSheet} from 'react-native';
import {Button, Text, Input} from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';

const styles = StyleSheet.create({
    heading: {
        padding: 20,
    },
});

export default class ContactForm extends React.Component
{
    constructor(props) 
    {
        super(props);

        this.state = {
            name: '',
            email: '',
        }
    }

    handleName(e)
    {
        this.setState({name: e.target.value})
        console.log(e.target.value);
    }

    handleEmail(e)
    {
        
    }

    submit(e)
    {
        console.log(this.state.name + " " + this.state.email);
    }

    render() 
    {
    return (
    <View style={styles.heading}>
        <Text h5>Sign up to receive updates/newsletters!</Text>
        <Input placeholder="your name" onChange={this.handleName.bind(this)} />
        <Input placeholder="your email" onChange={this.handleEmail.bind(this)} />
        <Button title="Submit" onPress={this.submit}/>
    </View>
    )
    }
}

【问题讨论】:

    标签: reactjs react-native react-native-firebase react-native-elements


    【解决方案1】:

    你好,你可以这样做,不需要将箭头函数与“this”绑定。

    export default class ContactForm extends React.Component
    {
        constructor(props) 
        {
            super(props);
    
            this.state = {
                name: '',
                email: '',
            }
        }
    
        handleName=(e)=>
        {   console.log(e);
            this.setState({name: e})
            
        }
    
        handleEmail=(e)=>
        {
            this.setState({email: e})
        }
    
        submit=()=>
        {
            console.log(this.state.name + " " + this.state.email);
        }
    
        render() 
        {
        return (
        <View style={styles.heading}>
            <Text h5>Sign up to receive updates/newsletters!</Text>
            <Input placeholder="your name" onChangeText ={this.handleName} /> 
            //change onChange to onChangeText 
            <Input placeholder="your email" onChangeText={this.handleEmail} />
            <Button title="Submit" onPress={this.submit}/>
        </View>
        )
        }
    }
    

    【讨论】:

    • 我已经尝试过了,但它仍然未定义。 e 没有任何价值,并且 e 是一个巨大的反应对象。
    • 你在使用 react native Input 吗?
    • React-native-elements,但它继承了所有原生 Input 功能。
    • 我已编辑我的答案并添加了评论,请尝试该解决方案一次
    • 这太疯狂了!我得到的每一份文档都表明您必须使用 'e.target.value' 将其更改为 (e) 并使用 onChangeText 使其工作!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 2017-05-08
    • 2019-12-03
    • 2021-12-09
    • 2019-12-05
    • 1970-01-01
    • 2019-09-20
    相关资源
    最近更新 更多