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