因此,我有一个自定义组件(TextButton),并将其包装在另一个组件(ContainedButton)中。我目前正在尝试设置ContainedButton的样式。但是,我想访问TextButton(主题)属性的值,并在设置ContainedButton样式时使用该值。
ContainedButton:
import React, { Component } from 'react';
import TextButton from './TextButton';
class ContainedButton extends Component {
render() {
const { style } = this.props;
return (
<TextButton {...this.props} style={[styles.containedButtonStyle, style]} />
);
}
}
const styles = {
containedButtonStyle: {
backgroundColor: (TextButton prop theme)
padding: 2,
borderWidth: 1,
borderRadius: 5
}
};
export default ContainedButton;
在“ backgroundColor”旁边的括号中,我想插入位于TextButton中的主题prop的值。我将如何实现这样的目标?
TextButton(如果需要):
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, style } = this.props;
return (
<TouchableOpacity onPress={onPress} style={style}>
<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;
答案 0 :(得分:0)
您可以获得theme
的值的方法与获取style
的值的方法相同:
const { theme } = this.props;
或将它们合并为一个语句:
const { style, theme } = this.props;