简体   繁体   中英

React Native - Is it possible to pass a Component in props to an other Component?

The idea is to pass the DetailView as props to a ListView component as:

//MainPage.js
...
import ItemsList from './ItemList';
import ItemDetail from './ItemDetail';

var items = [];
...
export default class extends React.Component {
render() {
    return (
      <View style={{flex: 1}}>
        <ItemsList
          ItemDetail=<ItemDetail/>
          items=items
        />
      </View>
    )
}

And the List

//ItemsList.js
...
...
export default class  extends React.Component {

  constructor(props) {
    super(props);
    var ds = new ListView.DataSource({
       rowHasChanged: (r1, r2) => r1 !== r2});
    this.state =  {
      dataSource: ds.cloneWithRows(this.props.items)
    }
  }

  render() {
    const { ItemDetail } = this.props.ItemDetail

    return (
      <View style={{flex:1}}>
      <ListView
        dataSource={this.state.dataSource}
        renderRow={(rowData, rowID) => <ItemDetail item={rowData} />}
      />
      </View>
    )
  }
}

The idea is just write a generic ItemList.

The trace of log show this.props.ItemDetail as a ReactElement but can not render properly

The Error is:

Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of StaticRenderer .

you are passing component as props in wrong way. You need to to it in following way instead.

export default class extends React.Component {
render() {
    return (
      <View style={{flex: 1}}>
        <ItemsList
          ItemDetail={ItemDetail}
          items=items
        />
      </View>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM