在react-native中,我们通常不扩展对象中所有内置的对象,而在其他编程语言中,例如swift,java,我们经常使用继承。在react-native中使用类继承有什么缺点

export default class A extends Component
{
}

export default class B extends A
{

}

最佳答案

只需将您的组件扩展为子组件即可。

class Label extends React.Component{
  constructor(props){
    super(props);
    this.className='plain-label';
  }
   render(){
     return <span className={this.className}>
        {this.props.children}
      </span>
   }
}


class SmallLabel extends Label{
  constructor(props){
    super(props);
    this.className = this.className + ' small-label';
  }
}

然后使用它:
class Main extends React.Component{
    render(){
      ....
      <Label> Plain Label </Label>
      <SmallLabel> SmallLabel </SmallLabel>
    }
}

在大多数情况下,继承都是一种可行的解决方案。因为扩展具有继承性的组件或多或少会导致某种情况,在这种情况下,行为无法无缝结合。但是,有了Composition,这是可能的。

检查此链接:https://reactjs.org/docs/composition-vs-inheritance.html

10-04 16:42