2017-12-18 86 views
1

在我的反應原生應用程序中,我只是試圖添加一個名爲RoundImageComponent的共享組件,並添加了一個RoundImageComponent.style以添加CSS樣式。使用此圓形圖像組件時,圖像的寬度將根據應用程序中的要求作爲道具傳遞。在一些情況下,寬度將不添加到組件標籤如下,如何設置默認樣式和用戶自定義樣式以動態地反應原生?

RoundImageComponent width={90} roundImage="https://media.wired.com/photos/593222b926780e6c04d2a195/master/w_2400,c_limit/Zuck-TA-AP_17145748750763.jpg" /> 

RoundImageComponent roundImage="https://media.wired.com/photos/593222b926780e6c04d2a195/master/w_2400,c_limit/Zuck-TA-AP_17145748750763.jpg" /> 

RoundImageComponent代碼

import React from 'react'; 
import { 
Text, 
View, 
} from 'react-native'; 
import Config from 'react-native-config'; 
import SplashScreen from 'react-native-splash-screen'; 
import RoundImageComponent from "./shared/avatar/RoundImageComponent"; 
import styles from './App.styles'; 

const resolveSession = async() => { 
// const session = sessionActions.getSession(); 
SplashScreen.hide(); 
}; 

setTimeout(() => { 
resolveSession(); 
}, 2000); 

const App =() => (
<View style={styles.container}> 
<RoundImageComponent width={90}roundImage="https://media.wired.com/photos/593222b926780e6c04d2a195/master/w_2400,c_limit/Zuck-TA-AP_17145748750763.jpg" /> 
</View> 
); 

export default App; 

RoundImageComponent

import { 
    StyleSheet, 
} from 'react-native'; 

import { container, primaryText } from '../../theme/base'; 


export const defaultImage = { 
height: 100, 
borderRadius: 50, 
width: 100 
} 
const styles = StyleSheet.create({ 
container: { 
...container, 
}, 
userDefinedImage: { 
...defaultImage, 
width: 40 
} 
}); 

export default styles; 

當用戶將寬度作爲道具傳遞時,應將圖像寬度覆蓋爲默認寬度,否則圖像寬度應保持爲默認寬度。 這樣可以嗎?

回答

1

這是通過道具的樣式可能。假設這是我CustomTextComponent

export CustomTextComponent = (props)=>{ 
    return (
     <Text style={[{fontFamily:"Lato", color:"#000", ...props.style}]}> 
       {props.children} 
     </Text> 
    ) 
} 

現在我想設置不同級別不同的顏色讓說紅色和綠色然後

red

<CustomTextComponent style={{color:'red'}}> 
      red colored text 
</CustomTextComponent> 

爲​​

<CustomTextComponent style={{color:'green'}}> 
      red colored text 
</CustomTextComponent> 

注意:您的...props.style應該在您的默認樣式之後。因爲你最後提到的將覆蓋前一個。 也可以利用default props value在某些情況下(LIB PropsType

+0

這種「<圖像樣式= {[styles.image,this.props.style]} 源= {{URI:this.props.roundImage 「} />」爲我工作。謝謝 –

+0

當使用這個「」,它會得到錯誤「Can not find variable:props 「 –

+0

你需要從你的調用中發送名稱風格的道具,如果statefull組件應該是'this.props.style'其他明智的'props.state'用於**演示組件** – Revansiddh

1

是的,這是可能的。

您可以通過在其之後傳遞另一個覆蓋當前樣式prop。它會看起來是這樣的:

const styles = StyleSheet.create({ 
    default: { 
    backgroundColor: red, 
    color: blue, 
    }, 
}); 

<View> 
    <DefaultComponent style={styles.default} /> 
    <CustomComponent style={[styles.default, { backgroundColor: none }]} /> 
</View> 

希望它可以幫助