如何使用自定义单元组件在ReactNative中实现ListView?

nbu*_*urk 4 javascript listview reactjs react-native

我正在构建一个ReactNative + Redux应用程序并正在使用该ListView组件.

_renderRow()其中ListView,我想返回我自己的单元组件(称为JobDetailCell仅从props管理ListView(被调用JobsRootComponent)的组件接收其中的数据).

到目前为止,我想出了以下代码:

JobsRootComponent.js

import React, {
  Component,
  StyleSheet,
  Text,
  View,
  ListView,
  ActivityIndicatorIOS,
  NavigatorIOS,
  TouchableHighlight
} from 'react-native'

import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { fetchJobs } from '../actions/Actions'
import { JobDetailCell } from './JobDetailCell'
import { JobDetailComponent } from './JobDetailComponent'

class JobsRootComponent extends Component {

  ...

  _renderRow(rowData) {
      const title = rowData.title
      const subtitle = rowData.by
      return (
        <JobDetailCell title={title} subtitle={subtitle}></JobDetailCell>
      )
  }

  ...

  render() {
    return (
        <ListView
          style={styles.container}
          dataSource={this.props.dataSource}
          renderRow={this._renderRow}
        />
      )
  }

  ...

}
Run Code Online (Sandbox Code Playgroud)

JobDetailCell.js

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

export default class JobDetailCell extends Component {

  render() {
    return (
      <View style={styles.cellContainer}>
        <Text style={styles.cellTitle}>{this.props.title}</Text>
        <Text style={styles.cellSubtitle}>{this.props.subtitle}</Text>
      </View>
    )
  }

}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行应用程序时,我在chrome dev控制台中收到以下错误:

ExceptionsManager.js:76警告:

React.createElement:类型不应该是null,undefined,boolean,或number.它应该是string(对于DOM元素)或ReactClass(对于复合组件).检查render 方法StaticRenderer.

谁能告诉我这里做错了什么?

Mot*_*Azu 5

问题是您以错误的方式导入组件.

这条线

import { JobDetailCell } from './JobDetailCell'
Run Code Online (Sandbox Code Playgroud)

相当于这一行:

var JobDetailCell = require('./JobDetailCell').JobDetailCell;
Run Code Online (Sandbox Code Playgroud)

由于您导出了没有命名字段的组件本身,因此未定义JobDetailCell.

这是您应该如何导入组件:

import JobDetailCell from './JobDetailCell'
Run Code Online (Sandbox Code Playgroud)