reactjs - 从导入的自定义组件中检索道具值
问题描述
所以我有一个自定义组件(TextButton),并将它打包在另一个组件(ContainedButton)中。我目前正在尝试设置 ContainedButton 的样式。但是,我想访问 TextButton(主题)道具的值,并在设置 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;
在“背景颜色”旁边的括号中,我想插入位于 TextButton 中的主题道具的值。我将如何实现这样的目标?
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;
解决方案
您可以像获得 的值theme
一样获得 的值style
:
const { theme } = this.props;
或者将它们组合成一个语句:
const { style, theme } = this.props;
推荐阅读
- or-tools - 定义不必访问的节点
- swift - 创建 NSManagedObject 子类...在我的项目中创建一个新错误
- cassandra - 测量 cassandra 集群中的吞吐量
- java - Appium 测试在我们应用程序的先前版本中有效,但在我们应用程序的新版本中并非全部有效
- cypress - 如何在柏树中测试元素的子元素?
- python - 无法使用 Visual Studio 2017(社区版)发布
- c++ - 带有自生成 CA、证书和客户端/服务器的“未知 ca”
- r - R Markdown 参数化报告是否需要 R Studio Connect 服务器?
- keras - 理解 SMAPE 的歧义
- tensorflow - 如何使用 Tensorflow 对象检测 API 继续训练对象检测模型?