javascript - 为什么我们不经常在 react-native 中使用继承?

标签 javascript reactjs react-native

在react-native中我们一般不会去extend all-ready built in objects,而在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>
    }
}

在大多数情况下都是继承——只是不是一个可行的解决方案。因为通过继承扩展组件或多或少会导致某些情况下,行为无法无缝结合。但是,通过组合,这是可能的。

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

关于javascript - 为什么我们不经常在 react-native 中使用继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57734538/

相关文章:

javascript - 如何让 scrollView 的内容在 react-native 中对齐顶部

javascript - 将鼠标悬停在其他元素下方

javascript - 在 jQuery 中从最高到最低的每个元素中添加数据属性

Javascript全局变量仅在匿名函数内更新

android - 在现有项目React-Native中添加现有原生项目Android

react-native - react 导航隐藏一个标签

javascript - AJAX 刷新后隐藏表中的 <td>

javascript - 范围问题 react 父子方法 ES6

javascript - 使用 VS Code 清理 React 文件中的格式

react-native - 如何在 react-native-element 中获得这种搜索栏样式?