2017-02-28 91 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

相关问题