React-Native:如何将Child组件包装在另一个类组件下

时间:2016-02-22 06:44:01

标签: reactjs react-native

让我用一个例子解释我的问题:

在SomeComponent.js中的

我有以下

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

      </View>
    )
  }
}

并在Root.js中导入&#39; SomeComponent&#39;如下

import SomeComponent from './SomeCoponent'
export default class SomeComponent extends React.Component {
  render() {
    return (
      <SomeComponent>
          <Text> hello </Text>
      </SomeComponent>
    )
  }
}

这是如何运作的?

我看到一些博客,有些人这样做:

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

        {/* code added here - start */}
        {React.Children.map(this.props.children, c => React.cloneElement(c, {
          route: this.props.route
        }))}
        {/* code added here - end */}

      </View>
    )
  }
}

但这对我不起作用。

我收到以下错误:

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components)

任何帮助将不胜感激。感谢

2 个答案:

答案 0 :(得分:23)

您可以使用此代码段

export default class SomeComponent extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
      <View style={{flex:1}}>
      {this.props.children}
      </View>
    )
  }
}

答案 1 :(得分:5)

你可以这样做

export default class SomeComponent extends React.Component {
  render() {
    return (
      <View>
        {this.props.children}
      </View>
    )
  }
}

<强> YupeComponent.js

import 'SomeComponent' from 'app/component/Somecomponent'
export default class YupeComponent extends React.Component {
  render() {
    return (
      <View style={{flex:1}}>
         <SomeComponent />
      </View>
    )
  }
}