简体   繁体   English

如何在 React Native 中创建子组件?

[英]How can I create sub component in react native?

I saw react native elements - Card component working like this.我看到 React Native 元素 - Card 组件是这样工作的。

<Card>
  <Card.Title>blahblah</Card.Title>
  <Card.Divider />
</Card>

I want to create a component with such sub component like Title and divider.我想创建一个包含标题和分隔符等子组件的组件。

I can create a component like this.我可以创建这样的组件。

class A extends Component {
}

How can I add a subcomponent(let's say Title) to A component?如何向 A 组件添加子组件(比如标题)?

Subcomponents are objects like the component itself but, they are passed to the main component as its keys.子组件是类似于组件本身的对象,但是它们作为键传递给主组件。 These two liks can be good help:这两个喜欢可以提供很好的帮助:

https://dev.to/ms_yogii/create-react-subcomponents-in-a-simple-way-5h1f https://dev.to/ms_yogii/create-react-subcomponents-in-a-simple-way-5h1f

https://dev.to/shayanypn/buckle-with-react-sub-component-10ll https://dev.to/shayanypn/buckle-with-react-sub-component-10ll

According to Reza's answer, I made a class component.根据Reza的回答,我做了一个class的组件。 Is this the right way?这是正确的方法吗? Please correct me if there is something wrong..如果有什么不对请指正。。

class Left extends Component {
  static id = 'Left';
  render() {
    return (
      <View>
        {this.props.children}
      </View>
    );
  }
};
class Right extends Component {
  static id = 'Right';
  render() {
    return (
      <View>
        {this.props.children}
      </View>
    );
  }
};
class SideBySide extends Component {
  protected others = [];
  constructor(props) {
    super(props);
    for(let i of this.props.children) {
      if(i.type.id == 'Left') this.left = i;
      else if(i.type.id == 'Right') this.right = i;
      else this.others.push(i)
    }
  }
  render() {
    return (
      <View style={{flexDirection: 'row', }}>
        {this.left}
        {this.right}
        {this.props.others}
      </View>
    );
  }
};
SideBySide.Left = Left;
SideBySide.Right = Right;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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