javascript - 从 React Native 中的其他组件获取 'inherit' 的最佳方式?

标签 javascript oop react-native

例如,如果我需要制作一个按钮的“小”和“大”版本,该按钮有很多(但不是全部)共同的方法和状态,那么实现此功能的最佳方法是什么 react native ?

我在简单地扩展“父”组件时遇到的问题(我对此可能是错误的)是使用 Props 一直很困惑。

我实现它的方式只是为“父”组件提供一个 bool 属性(在本例中,表示“小”或“大”),然后根据该 bool 值更改其功能。 “子”组件几乎只是为了可读性而存在。

最佳答案

只需扩展您的组件即可创建子组件。

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,这是可能的。

扩展/子类化 React 组件的良好实践,请参阅:https://discuss.reactjs.org/t/best-practices-for-extending-subclassing-components/1820/3

关于javascript - 从 React Native 中的其他组件获取 'inherit' 的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47246039/

相关文章:

javascript - 使用 React Hooks 进行条件渲染 : loading

javascript - D3 防止双击缩放

javascript - React,在下拉菜单中使用表情符号

ruby - 如何在 ruby​​ 中使基类方法不可重写?

javascript - 我应该使用公共(public)方法访问类中的私有(private)变量吗?

oop - 为什么 Dart 更喜欢省略局部变量的类型注释?

javascript - 如何将应用程序状态的答案作为 Prop 而不是卡的内部状态传递

javascript - 如何同时为多个元素应用悬停事件?

javascript - 如何与 Chrome 打包 App 中的沙盒窗口通信?

cordova - Native Script 与 react native 和 ionic 框架的区别