2016-12-01 43 views
0

對於我的生活,我無法弄清楚爲什麼這一小部分代碼將無法正常工作!反應原生按鈕導致不變無效

我已經將問題隔離到Button元素(導入語句看起來不錯)。

我看到錯誤「不變的違規:元素類型無效:期望一個字符串(對於內置組件)或一個類/函數(對於複合組件),但得到:undefined。檢查Login的渲染方法。

import React, { ScrollView, Image, StyleSheet, Button } from "react-native"; 
import { connect } from "react-redux/native"; 

const onButtonClicked =() => { 

}; 

class Login extends React.Component { 
    componentDidMount() { 

    } 

    render() { 
     return (
      <ScrollView style={{flex: 1}} 
         contentContainerStyle={{ 
          justifyContent: "center", 
          alignItems: "center" 
         }}> 
       <Image source={require('../../img/coin.png')} 
        resizeMode={Image.resizeMode.cover} 
        style={Styles.coinLogo} /> 

       <Button title="Login default" 
         onPress={() => {}} /> 
      </ScrollView> 
     ); 
    } 
} 

Login.propTypes = { 
    dispatch: React.PropTypes.func 
}; 


Login.defaultProps = { 
    dispatch:() => {} 
} 

const Styles = StyleSheet.create({ 
    coinLogo: { 
     marginTop: 50, 
     height: 200, 
     width: 200, 
    }, 
    loginButton: { 
     marginTop: 50, 
    }, 
}); 

export default connect((state) => ({ 

}))(Login); 

回答

2

這是一個討厭的問題,因爲該錯誤信息是非常模糊的,具有做的(我認爲)與對象解構

當你解構的對象,說:。

var myObject = {a: 1, b: 2, c: 3}; 

let {a, b, c, d} = myObject; 

你transpiler執行以下操作:

let a = myObject.a; 
let b = myObject.b; 
let c = myObject.c; 
let d = myObject.d; // Ah! But we never defined a 'd' key, did we? 

和當然,不存在的鍵評估,以undefined而不產生錯誤,所以你得到的是d具有undefined值。

讓我們回到您的導入。我覺得他們應該是這樣的:

import React from 'react'; // The React API moved to the react package, you should be getting an error because of this. See https://github.com/facebook/react-native/releases/tag/v0.26.0 (Unless you are using React Native <= 0.25) 
import { ScrollView, Image, StyleSheet, Button } from "react-native"; 
import { connect } from "react-redux"; // As far as I know, the connect is exported directly from 'react-redux', but it might be OK the way you had it. 

現在,讓我們去你render。我們正在嘗試呈現ScrollViewImageButton。 RN正在提高誤差,因爲其中一個正在評估爲undefined,這是不允許的,但它並沒有告訴我們哪一個。你可以嘗試和三個值,並檢查哪一個是未定義的。但是,我強烈認爲它是Button,因爲它是在RN 0.37中添加的,正如我之前在導入React時所提到的那樣,您必須運行0.26.0標記之前的RN版本,否則代碼將會產生一個不同的錯誤。

讓我知道如果是這樣的話。

+0

不是。它看起來像我的項目甚至沒有引用React包,所以我安裝了它,但結束了相同的錯誤。 – Steven

+0

我正在使用此處找到的樣板項目:https://github.com/FormidableLabs/formidable-react-native-app-boilerplate.git 您可以通過向app.js添加按鈕來快速查看問題。 並感謝您花時間回答! – Steven

+0

與原生變化的反應速度相比,這是一個非常古老的樣板。你有沒有試過將console.log作爲martinarroyo的建議。如果你沒有更新該樣板的依賴關係,那麼肯定Button是未定義的,如果你不想更新依賴項,你應該使用TouchableOpacity或TouchableHighlight而不是Button。 – diedu