【问题标题】:onChangeText giving Error in react nativeonChangeText 在本机反应中给出错误
【发布时间】:2020-09-06 13:16:38
【问题描述】:

我有以下代码

   import React from 'react';
   import { StyleSheet,Text,View,SafeAreaView,ScrollView ,Image ,TextInput} from 'react-native';     
   import  Entypo  from 'react-native-vector-icons/Entypo';
   import { Neomorph } from 'react-native-neomorph-shadows';

export const HomeScreen = ({ navigation }) => {
  state = {
    fname : "",
    sname : "",
  }
  
  return(  <SafeAreaView style={{ alignSelf: "stretch" }}>
            <View style={styles.card}>
              <Neomorph style={styles.neomorph} >
                <Text style={styles.input_title}>First Name</Text>
                  <Neomorph inner style={styles.input} >
                  <TextInput
                    style={{ borderColor: 'transparent', borderWidth: 1 ,width: "100%" ,borderRadius: 8,height: 50,paddingLeft: 10,fontSize: 18,fontWeight:"bold",color:"#ffffff"}}
                    onChangeText={(nextValue) => this.setState({fname: nextValue})}
                    value={this.state.fname}
                  />
                  </Neomorph>
              </Neomorph>
            </View>
            <View style={styles.card}>
              <Neomorph style={styles.neomorph} >
                <Text style={styles.input_title}>Second Name</Text>
                  <Neomorph inner style={styles.input} >
                  <TextInput
                    style={{ borderColor: 'transparent', borderWidth: 1 ,width: "100%" ,borderRadius: 8,height: 50,paddingLeft: 10,fontSize: 18,fontWeight:"bold",color:"#ffffff"}}
                    onChangeText={(nextValue) => this.setState({sname: nextValue})}
                    value={this.state.sname}
                  />
                  </Neomorph>
              </Neomorph>
            </View>
 </SafeAreaView>
)
}
onChangeText 我收到这样的错误

TypeError: _this.setState is not a function. (In '_this.setState({
          fname: nextValue
        })', '_this.setState' is undefined)

谁能帮我解决这个问题 提前致谢

【问题讨论】:

    标签: react-native react-native-android setstate


    【解决方案1】:

    您正在使用功能组件,因此那里不支持状态。

    您可以切换到基于类的组件,如下所示

    export class HomeScreen extends Component {
      state = {
        fname : "",
        sname : "",
      }
      
      render()
    {
     //return jsx
    }
    }
    

    或者使用下面的 useState 钩子

    export const HomeScreen = ({ navigation }) => {
      const [fname,setfname] = React.useState("");
      
      return()
    }
    

    你可以使用 setfname("value") 来设置值。

    【讨论】:

    • 感谢@GuruparanGiritharan,但为此我需要调用handlefname 和handleSname 函数,但我试图在TextInput 内部的同一行中执行此操作吗?
    • 使用基于类的组件的第一个选项,然后您将可以访问状态
    • 但我必须使用导航,如何在基于类的组件中使用它?
    • 您可以通过“this.props.navigation”访问导航,它将作为道具传递:)
    猜你喜欢
    • 2020-01-26
    • 2022-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 2021-11-19
    相关资源
    最近更新 更多