在我的本机应用程序中,我只是尝试添加一个名为 RoundImageComponent 的共享组件,并添加了一个 RoundImageComponent.style 来添加css样式。使用此Round图像组件时,图像的宽度将根据应用程序中的要求作为props传递。在某些情况下,宽度不会添加到组件标记中,如下所示,
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;
当用户将宽度作为道具传递时,图像宽度应覆盖到默认宽度,否则图像宽度应保留为默认宽度。 这样可以吗?
答案 0 :(得分:4)
这可以通过将props传递给样式来实现。假设这是我的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>
代表green
<CustomTextComponent style={{color:'green'}}>
red colored text
</CustomTextComponent>
注意:您的...props.style
应该是您的默认样式之后。因为你上次提到的将覆盖前一个。
在某些情况下,您还可以使用default props value
。(lib PropsType
)
答案 1 :(得分:1)
是的,这是可能的。
您可以通过在其后面传递另一个来覆盖当前样式道具。它看起来像这样:
const styles = StyleSheet.create({
default: {
backgroundColor: red,
color: blue,
},
});
<View>
<DefaultComponent style={styles.default} />
<CustomComponent style={[styles.default, { backgroundColor: none }]} />
</View>
希望有所帮助