React-Native child 组件不呈现 parent 组件内的信息

React-Native the child component don't render the information within the parent component

我正在开发一个使用 ScrollView 的 React Native 应用程序。我想显示一定数量的项目(一张带有标题和 child 组件的卡片)。

当我必须渲染每个项目时,问题就来了,而 parent 可以渲染,而 child 不能。

我不知道问题出在哪里,这是我的代码:

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

    const mismo =[
     'Mismo',
     'Mismo',
     'Mismo',
     'Mismo',
     'Mismo'
    ];


    class Mismo extends Component {


     renderMismo2(){
       mismo.map((item) =>{
       return(
         <View>
           <Text>{item}</Text>
         </View>
       )
     })
    }

  render(){
    return(
      <View>
      {this.renderMismo2()}
      </View>
    );
  }
}

export default Mismo;

=================================

import React, {Component} from 'react';
import {View, Text, ScrollView} from 'react-native';
import {Card} from 'react-native-elements';

import PriceCard from '../components/PriceCard';
import Mismo from '../components/Mismo';


class OrderPricingCard extends Component{
  renderAllPrices(){
    this.props.data.orders.map((item, i) => {
      return(
        <View>
          <PriceCard
            key={item.transporterName}
            data={item}
          />
        </View>
      );
    })
  }

  renderMismo(){
    return(
      <Mismo />
    );
  }

  render () {
    return (
      <Card
        containerStyle={styles.cardContainer}
        title={`Pedido: ${this.props.data.id}`}
      >
        <ScrollView
          horizontal
        >
            {this.renderMismo()}

            {this.renderAllPrices()}



        </ScrollView>
      </Card>
    );
  }
}

const styles = {
  cardContainer:{
    borderRadius: 10,
    shadowColor: "#000",
    shadowOffset: {
        width: 0,
        height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  }

}

export default OrderPricingCard;

这是一个很容易犯的错误!我已经做过好几次了。发生的事情是您忘记了在每个组件中找到的渲染方法(renderMismo2()renderAllPrices())的 return 语句。尽管 map 方法正确地具有 return 语句,但您实际上并没有从函数本身 returning 任何东西。

如果您要 console.log() React render() 方法中 return 上方的任何一个函数调用,您将在控制台中看到 undefined

这是修正后的样子。

renderAllPrices(){
    // added the 'return' keyword to begin the line below
    return this.props.data.orders.map((item, i) => {
      return(
        <View>
          <PriceCard
            key={item.transporterName}
            data={item}
          />
        </View>
      );
    })
  }

 renderMismo2(){
   // same here, added the 'return' keyword
   return mismo.map((item) =>{
   return(
     <View>
       <Text>{item}</Text>
     </View>
   )
 })
}

我在 React Native 沙箱中测试了上面的内容并且它有效。希望对您有所帮助!