2017-02-28 96 views
0

我有一個錯誤,真的不知道爲什麼。這是一個檸簡單的代碼中庸之道測試反應過來人,想創建一個類誰打電話的其他類和UNE一個按鈕來增加數量:React Native JS:預計一個組件類,得到[對象對象]

import React, { Component } from 'react'; 
import { 
    AppRegistry, 
    StyleSheet, 
    TouchableHighlight, 
    Text, 
    View 
} from 'react-native'; 

export default class Apprentissage1 extends Component { 
    render() { 
    return (
     <View style={styles.container}> 
     <Text style={styles.welcome}> 
      Welcolm bitch 
     </Text> 
     <Product name="Product 1"/> 
     <Product name="Product 2"/> 
     </View> 
    ); 
    } 
} 

class Product extends Component { 

    constructor(props) {        //Constructeur 
     super(props); 
     this.state = { 
      quantity: 0 
     }; 
    } 


    addToCart(){ 
    this.setState({ 
     quantity: this.state.quantity + 1 
    }) 
    } 
    render(){ 
    return(
     <View style={styles.container}> 
      <h2>{this.props.name}</h2> 
      <p>Quantity: {this.state.quantity}</p> 
      <TouchableHighlight onPress={this.addToCart.bind(this)}> 
      Add To cart 
      </TouchableHighlight> 
     </View> 
    ); 
    } 
} 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    justifyContent: 'center', 
    alignItems: 'center', 
    backgroundColor: '#F5FCFF', 
    }, 
    welcome: { 
    fontSize: 20, 
    textAlign: 'center', 
    margin: 10, 
    }, 
    instructions: { 
    textAlign: 'center', 
    color: '#333333', 
    marginBottom: 5, 
    }, 
}); 

AppRegistry.registerComponent('Apprentissage1',() => Apprentissage1); 

感謝的對你有所幫助:)

+1

你不能渲染的反應,本機應用程序的HTML,而無需使用的WebView組件...此錯誤是在你的產品組件 – Maxwelll

+0

嘗試從''刪除'''出口default'''相關的渲染功能'導出默認類Apprentissage1擴展組件{'''並用原生組件替換html組件'''''' –

回答

0

我不知道錯誤觸發的位置,但您的onPress對於TouchableHighlight只能是() => { this.setState({quantity: this.state.quantity + 1}) }而不是this.bind.addToCart(this)

-1

將產品類別分離爲新文件,然後導入它。 React Native並不喜歡在同一個文件中有多個組件。

你是怎麼初始化項目的?什麼是錯誤信息?

+1

這是不正確的。只要只有一個默認導出,React Native在同一文件中具有多個組件就沒有問題。 – TheJizel

2

將您的<h2><p>標記替換爲React Native <View>組件。

您無法在您的React Native應用程序中使用DOM元素。

+0

好的。這肯定會導致問題。 – TheJizel

+0

謝謝,它的工作!我已經有一個其他的錯誤whith 元素必須有一個子元素(我在內部 BlackStef

1

這是因爲您使用的是非組件元素,如h2,p是html元素,而不是反應原生組件。 用於此的正確組件是Text 然後對h2和p都使用文本。只需操縱其fontSize以滿足您的需求。

<Text style={{ fontSize: 18 }}>{this.props.name}</Text> 
<Text style={{ fontSize: 12}}>Quantity: {this.state.quantity}</Text> 

另外ToucheableHighlight應該包含單個元素而不是字符串。

<ToucheableHighlight 
    onPress={this.addToCart.bind(this)} 
    > 
    <Text> 
     Add to Cart 
    </Text> 
    </ToucheableHighlight> 
+0

)謝謝,它的工作!我已經有了另一個錯誤whith 元素必須有一個子元素(我內部 BlackStef

+0

@BlackStef太棒了!編輯我的答案,包括如果有人需要它。 – Damathryx

相關問題