输入值仅在React Native中返回未定义

时间:2020-07-16 16:43:08

标签: javascript ios reactjs react-native use-state

我对本机做出了新的反应,并试图加载我的第一个基本应用程序的主页。目前,它要求用户输入其“名称”和“ networth”,而我只想返回networth输入乘以一个常数,并带有一个警告,该警告在按Submit并显示“ {name} +“ net net will be” + { newNetworth} +“明年!”。但是现在我的输出是:“明年未定义就值得!”而且我一生都无法弄清楚如何使实际值通过。

这是我的孩子部分:

mixer.xml

这是我的父级组件:

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

class OpeningPageQs extends React.Component {
  
    
    state = {
    name: '',
    networth: 0,
    newNetworth: 0
}

nextYearWorth() { 
    

    this.setState({
        name: this.state.name,
        newNetworth: this.state.networth * 1.1
    });
return (alert(this.name + ' will be worth ' + this.newNetworth + ' next year!'));

}


    render (){
        

        return (
        <View>
            <TextInput style= { styles.input }
                placeholder= "name"
                onChangeText= { this.name }
            />

            <TextInput style= { styles.input }
                placeholder= 'networth'
                onChangeText= { this.networth }
            />

            <TouchableOpacity style = {styles.submitButton}
            onPress = {
                () =>  this.nextYearWorth(this.state.name, this.state.networth)
            }
            >
             
                <Text style={styles.submitButtonText}>
                Submit
                </Text>
                </TouchableOpacity> 
        </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        paddingTop: 23
    },

    input: {
        margin: 15,
        height: 40,
        borderColor: '#7a42f4',
        borderWidth: 1
    },
    submitButton: {
        backgroundColor: '#7a42f4',
        padding: 10,
        margin: 15,
        height: 40,
     },
     submitButtonText: {
         color: 'white'
     }
})


export default OpeningPageQs;

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

参考:https://reactnative.dev/docs/textinput

您错误地设置了状态。尝试这样:

        <TextInput style= { styles.input }
           placeholder= "name"
           onChangeText={text => this.setState({name: text})}
        />

可能不值得仅仅为了显示结果而设置状态。您可以在nextYearWorth方法中创建局部变量,也可以在onChangeText回调中设置状态时将该值乘以该值。

对于警报-请查看模态组件:https://reactnative.dev/docs/modal#docsNav

答案 1 :(得分:0)

您可以那样使用。

const server = createServer();

server.express.use(cookieParser());

// decode the JWT so we can get the user Id on each request
server.express.use((req, res, next) => {
  const { token } = req.cookies;
  if (token) {
    const { userId } = jwt.verify(token, process.env.APP_SECRET);
    // put the userId onto the req for future requests to access
    req.userId = userId;
  }
  next();
});