设置导入的自定义组件的样式



所以我正在导入一个自定义组件TextButton并将其打包到另一个OutlinedButton中。我导出类OutlinedButton期望看到传递的道具和添加的新样式进行渲染。但是,只有道具被正确渲染。我添加的额外样式根本没有出现。关于为什么会发生这种情况的任何想法?

import React, { Component } from 'react';
import TextButton from './TextButton';
class OutlinedButton extends Component {
render() {
return (
<TextButton {...this.props} style={styles.outlineButtonStyle} />
);
}
}
const styles = {
outlineButtonStyle: {
borderWidth: 1
}
};
export default OutlinedButton;

文本按钮类(有点长(

import React, { Component } from 'react';
import { Text, TouchableOpacity } from 'react-native';
import PropTypes from 'prop-types';
class TextButton extends Component {    
constructor(props) {
super(props);
this.state = {};
}
componentWillMount() {}
componentWillReceiveProps(newProps) {
if (newProps.theme !== this.props.theme) {
this.determineTheme(newProps.theme);
}
if (newProps.size !== this.props.size) {
this.determineSize(newProps.size);
}
}
// set the theme
determineTheme = function (theme) {
if (theme === 'primary') {
return {
color: '#0098EE'
};
} else if (theme === 'secondary') {
return {
color: '#E70050'
};
} else if (theme === 'default') {
return {
color: '#E0E0E0'
};
} 
return {
color: '#E0E0E0'
};
}
// set the size
determineSize = function (size) {
if (size === 'small') {
return {
fontSize: 16
};
} else if (size === 'medium') {
return {
fontSize: 22
};
} else if (size === 'large') {
return {
fontSize: 28
};
}
return {
fontSize: 22
};
}
render() {
const { onPress, children, theme, size } = this.props;
return (
<TouchableOpacity onPress={onPress}>
<Text style={[this.determineTheme(theme), this.determineSize(size)]}>{children}</Text>
</TouchableOpacity>
);
}
}
TextButton.propTypes = {
onPress: PropTypes.func,
title: PropTypes.string,
theme: PropTypes.string,
size: PropTypes.string
};
export default TextButton;

您没有使用传递给TextButton组件的style道具:

render() {
const { onPress, children, theme, size, style } = this.props;
return (
<TouchableOpacity onPress={onPress} style={style}>
<Text style={[this.determineTheme(theme), this.determineSize(size)]}>{children}</Text>
</TouchableOpacity>
);
}

当您在组件中按如下方式设置样式<TextButton>时,您不是在组件上设置样式,而是将其作为 props 传递给组件。因此,您必须以 this.props.style<TextButton>访问它,并将其应用于子组件中,如下所述。希望你明白了。

render() {
return (
<TextButton {...this.props} style={styles.outlineButtonStyle} />
);
}
}
const styles = {
outlineButtonStyle: {
borderWidth: 1
}
};

模拟示例:https://codesandbox.io/s/wn9455x58

最新更新