簡體   English   中英

React Native:樣式 props.children

[英]React Native: styling props.children

假設我有一個按鈕組件。 我可以從不同的屏幕導入它,它的行為是獨立的。 我可以給它不同的子項(文本、圖像、文本 + 圖標、圖標等)。

這看起來像這樣:

import React from 'react';
import { TouchableOpacity } from 'react-native';

import theme from '$/theme';

const styles = StyleSheet.create({
  button: {
    backgroundColor: 'red',
  },
  text: {
    fontFamily: 'Nunito',
    color: 'white',
  },
  icon: {
    color: 'grey',
  }
});

export default (props) => (
  <TouchableOpacity {...props} style={styles.button}>
    {props.children}
  </TouchableOpacity>
);

然后

// I want to be able to do either without having to style Text/Icon each time
const button1 = <Button><Text>Click</Text></Button>
const button2 = <Button><Icon name="back" /></Button>

我想直接在按鈕組件中定義圖標、文本等的樣式,對嗎? 當存在於孩子中時,是否可以將styles.text變量傳遞給 Text 組件? 圖標、圖像等同上嗎?

我不覺得每次都必須滿足孩子們的風格是一種很好的做法。 然而,我可以使用<Button text={'Click'} />語法然后播放 if/else 語句,但我不喜歡為內容傳遞屬性。

只需將文本或圖標作為道具傳遞給Button組件

export default (props) => (
  <TouchableOpacity {...props} style={styles.button}>
    {props.title && <Text style={styles.text}>{props.title}</Text>}
    {props.icon && <Icon name={props.icon} />}
  </TouchableOpacity>
);

或者,創建ButtonTextButtonIcon組件。

您可以使用React.cloneElement

export default (props) => (
  <TouchableOpacity {...props} style={styles.button}>
    {this.renderChildren()}
  </TouchableOpacity>
);

renderChildren() {
    return this.props.children.map(children => {
        return React.cloneElement(children, {style: { color: 'grey', fontFamily: 'cochin' }});
    })
}

但這就是是否要使用相同的樣式而不管組件的類型如何。 它將使向下傳遞的圖標和文本變為灰色。

我們為React Native提供了一個很好的Essential跨平台UI組件,名為nativebase.io ,它具有簡單而完整的組件。 使用nativebase.io,我們可以制作HTML之類的組件。 例如此代碼:

const styles = StyleSheet.create({
  button: {
    backgroundColor: 'red',
  }
});

export default (props) => (
  <TouchableOpacity {...props} style={styles.button}>
    {props.children}
  </TouchableOpacity>

現在是:

<Button><Text>Click</Text></Button> //without any const

完整的組件(如Tabs Header Body Icon和...)存在於nativeBase的文檔中。

祝好運

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM