【问题标题】:How to access, send props in const type views - React Native?如何在 const 类型视图中访问、发送道具 - React Native?
【发布时间】:2021-03-14 06:18:55
【问题描述】:

我正在学习在不使用类扩展组件的情况下使用 typescript 创建 API 的方法。 实际上,我不知道如何从 const 视图访问 props 并将其发送到另一个函数:

App.tsx

import React, {useState} from 'react';
import { NavigationContainer, StackActions } from '@react-navigation/native';
import Navigator from './Components/Navigator';
import { Root } from 'native-base';
import * as Font from 'expo-font';
import AppLoading  from 'expo-app-loading';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import rootReducer from './Store/Reducers/Reducers';

const store = createStore(rootReducer);

export default class App extends React.Component {
  constructor(props) {
    super(props);
   this.state = { loading: true };
}

async componentDidMount() {
   await Font.loadAsync({
   Roboto: require('native-base/Fonts/Roboto.ttf'),
   Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'),
 });
 this.setState({ loading: false });
}

render(){
  if (this.state.loading) {
    return (
      <Root>
        <AppLoading />
      </Root>
    );
  }
  else {
    return (
      <Provider store={store}>
        <Root>
           <NavigationContainer>
             <Navigator/>
            </NavigationContainer>
        </Root>
      </Provider>          
    );
  }
 }
}

Navigator.tsx

import React from 'react'
import { createStackNavigator } from '@react-navigation/stack'
import Login from '../Views/Login'
import Home from '../Views/Home'

const Stack = createStackNavigator();

const Navigator= () =>{
  return (
        <Stack.Navigator>
            <Stack.Screen name="Login" component={Login}  options={{headerShown:false}}/>
            <Stack.Screen name="Home" component={Home} options={{title:'Home.'}}/>
        </Stack.Navigator>
  );
}

export default Navigator;

Login.tsx我正在尝试发送有关按钮功能的道具...

import React, {useState} from 'react'
import {Text, TextInput, View, Image } from 'react-native'
import {Button, Toast, Content} from 'native-base'
import {Auth} from '../Services/Auth/AuthService'

const Login=({navigation})=>{
   const [userName, setUserName] =useState('');
   const [password, setPassword] =useState('');
   const [resultLog, setResultLog] = useState('');

   return( 
     <View>
        <TextInput placeholder="Username..." defaultValue={userName} onChangeText={txt=> setUserName(txt)} />
        <TextInput placeholder="Password..." defaultValue={password} onChangeText={txt=> setPassword(txt)}  secureTextEntry={true}/>
        <Button primary style={{width:115, height:45, marginBottom:15}} onPress={()=> ValidateFields(userName, password, this.props)? navigation.navigate('Home') : Toast.show({
            text: resultLog})}> 
            <Text style={{color:'white'}}>Login</Text> 
        </Button>
        <Button bordered  onPress={()=> navigation.navigate('Register')}> 
            <Text style={{color:'red'}}>Register </Text> 
        </Button>
     </View>
   );
}

async function ValidateFields(userName:string, password:string, props:any){
   await Auth.LoginUser({nick:userName, password: password}, props);
   //...
}

export default Login;

AuthService.tsx我正在尝试接收 props 并在使用 dispatch for redux 之后......。)

export const Auth={
    LoginUser,
}

interface IAuthData{
   nick : string,
   password : string
};

async function LoginUser(AuthData:IAuthData, props: any){
  try{
      console.log(props);
      let response = await fetch('http://localhost/user/Login/authentication', 
                                                                    {method: 'POST',
                                                                    headers: {
                                                                    Accept: 'application/json',
                                                                    'Content-Type': 'application/json'
                                                                    },
                                                                    body: JSON.stringify(AuthData)
      });

      let json = await response.json();      
      if(response.status==200){
          props.dispatch(//...code here);
      }
  }catch(err){
     console.error(err);
  }
}

当我按下登录按钮时,出现错误:

undefined 不是一个对象(评估 '_this.props')

【问题讨论】:

    标签: javascript typescript react-native react-redux


    【解决方案1】:

    您在功能组件中使用this.props。它仅适用于类组件。在你的情况下,你可以做的是

    const Login=(props)=>{
    
       const {navigation} = props; // add here 
       .....
    
       return( 
         <View>
            .....
            // change here, replace "this.props" to "props" only
           <Button onPress={()=> ValidateFields(userName, password, props)? navigation.navigate('Home') : Toast.show({
                text: resultLog})}> 
                <Text style={{color:'white'}}>Login</Text> 
            </Button>
         </View>
       );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多