对组件进行 react-native 类型检查

react-native type check on component

我有一个组件,我希望能够处理两种组件。一个是文本组件,另一个是图像组件。

我有一些默认样式,比如我希望能够将其应用于两个组件的颜色,但是,文本元素可以在其样式中使用颜色键,但在图像上,它必须是 tintColor关键。

有什么方法可以检查我有哪些元素,以便为每个元素设置适当的样式?

如果我没理解错的话,你可以使用3种样式对象来处理它:

const styles = StyleSheet.create({
  default: { marginTop: 10, borderWidth: 1 },
  onlyButton: { borderColor: '#F0F' },
  onlyText: { borderColor: '#C9F' },
})

<Text style={[styles.default, styles.onlyText]} />
<TouchableOpacity={[styles.default, styles.onlyButton]} />

请注意,上面的代码可能有拼写错误,这只是一个展示这个想法的例子。

让我知道是否有帮助,或者如果我误解了你的问题。

希望对您有所帮助

你会发现很多组件都有这样的行为,包括一些官方组件。

例如:<ScrollView />stylecontentContainerStyleindicatorStyle

对于您的组件,它可以是:

<CompositeComponent
  style={{backgroundColor: 'red'}}
  textStyle={{color: 'black'}}
  imageStyle={{tintColor: 'black'}}
  />

并在您的 render() 函数中,

render() {
  return (
    <View>
      <Text style={{[this.props.style, this.props.textStyle]}} />
      <Image style={{[this.props.style, this.props.imageStyle]}} />
    </View>
  );
}

这样 <Text /><Image /> 共享相同的 style,然后用 textStyleimageStyle.

分别覆盖