首页 > 解决方案 > 从导入的自定义组件中检索道具值

问题描述

所以我有一个自定义组件(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;

标签: reactjsreact-native

解决方案


您可以像获得 的值theme一样获得 的值style

const { theme } = this.props;

或者将它们组合成一个语句:

const { style, theme } = this.props;

推荐阅读