我有一个非常简单的组件,名为Divider
,这里是源代码:
import React from "react";
import { StyleSheet, View } from "react-native";
export default class Divider extends React.Component {
render() {
return (
<View style = { styles.separator } />
);
}
}
const styles = StyleSheet.create({
separator: {
height: StyleSheet.hairlineWidth,
marginBottom: 8,
backgroundColor: "#FFFFFF80",
},
});
我试图实现的是,styles.separator
中的值成为该组件的默认值,因为这些值是我在大多数情况下使用的值,但在某些边缘情况下,我需要将marginBottom
更改为16
。
所以大多数情况下我只想做<Divider />
,但有时<Divider marginBottom = 16 />
我现在看到的是下面这样的东西,但是很明显这是行不通的。
import React from "react";
import { StyleSheet, View } from "react-native";
export default class Divider extends React.Component {
static defaultPropts = {
marginTop: 0,
marginBottom: 8,
backgroundColor: "#FFFFFF80",
}
render() {
return (
<View style = {{
height: StyleSheet.hairlineWidth,
marginTop: {this.props.marginTop},
marginBottom: {this.props.marginBottom},
backgroundColor: {this.props.backgroundColor},
}} />
);
}
}
发布于 2017-09-12 06:43:16
因此,经过一番研究后,我发现这是可行的。
import React from "react";
import { Dimensions, StyleSheet, View } from "react-native";
export default class Divider extends React.Component {
static defaultProps = {
customWidth: Dimensions.get("window").width / 2.0,
}
render() {
const halfWidth = this.props.customWidth
return (
<View style = { [styles.separator, {width: halfWidth}] } />
);
}
}
const styles = StyleSheet.create({
separator: {
height: StyleSheet.hairlineWidth,
backgroundColor: "#FFFFFF80",
},
});
所以现在每当我使用<Divider />
时,它的宽度将是屏幕大小的一半,但是如果我使用<Divider customWidth = { 10 }
,那么它将覆盖默认值,而不是10 dp。
发布于 2017-09-12 05:30:12
您可以通过道具接收自定义样式,并将它们作为数组在组件样式中使用。当您在组件的后面调用道具样式时,它将覆盖它已经拥有的任何相同的样式属性。
例如,假设您有一个名为“Card”的组件,您可以这样编写您的组件:
<View style={[style.cardStyle, props.style]}>
{props.children}
</View>
把它叫做<Card style={{ backgroundColor: '#FFFFFF'}} />
因此,它从自己的组件中获得了所有定义的“cardStyle”,还添加了道具接收到的样式。
希望能帮上忙。
编辑:
你可以试试这样的东西
import React from "react";
import { StyleSheet, View } from "react-native";
const Divider = (props) => {
<View style = {{
height: StyleSheet.hairlineWidth,
marginTop: {this.props.marginTop},
marginBottom: {this.props.marginBottom},
backgroundColor: {this.props.backgroundColor},
}} />
}
Divider.defaultProps = {
marginTop: 0,
marginBottom: 8,
backgroundColor: "#FFFFFF80",
}
export default Divider;
如果对你有用的话请告诉我。
发布于 2017-09-12 05:28:58
你可以这样做
export default class Divider extends React.Component {
render() {
return (
<View style = {{
height: StyleSheet.hairlineWidth,
marginTop: {this.props.marginTop},
marginBottom: {this.props.marginBottom},
backgroundColor: {this.props.backgroundColor},
}} />
);
}
}
Divider.defaultProps = {
marginTop: 0,
marginBottom: 8,
backgroundColor: "#FFFFFF80",
}
https://stackoverflow.com/questions/46177518
复制相似问题