2017-12-18 211 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> 

希望它可以帮助