【问题标题】:Inheriting style from parent从父级继承样式
【发布时间】:2020-06-05 04:20:10
【问题描述】:

我正在尝试为链接添加悬停功能,其中包含一个名为 <HoverLink /> 的类

像这样:

import { Hoverable } from 'react-native-web-hooks';

class HoverLink extends Component {

    render() {
        return (
            <Hoverable >
                {isHovered => (
                    <View accessible style={{ backgroundColor: isHovered ? '#333' : '#fff' }}>
                        <Link {...this.props} >{this.props.children}</Link>
                    </View>
                )}
            </Hoverable>
        )
    }
}

这就是我使用它的方式:

<HoverLink style={WebPseudoStyles.footerLinks} target="_blank" src="https://resources.allsetlearning.com/chinese/grammar/Main_Page">Chinese Grammar Wiki</HoverLink>

但是,当我尝试传递我的样式时,我收到以下错误:

Invariant Violation: The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.

如何使用从父级/HOC 传入的样式?我正在四处寻找是否有办法做到这一点,但我没有看到任何具体的内容。

和WebPseudoStyles:

export const WebPseudoStyles = StyleSheet.create({
    footerLinks: {
        color: footerTextColor,
        textDecoration: "none",
        fontFamily: fontFamily,
        marginBottom: 15
    },
    socialIcons: {
        textDecoration: "none",
        fontFamily: fontFamily,
    },
    socialIconsContainer: {
        backgroundColor: "#1e2234",
        paddingLeft: 10,
        paddingRight: 10, paddingTop: 10,
        paddingBottom: 10,
        marginLeft: 10,
        marginRight: 10,
        width: 50,
        height: 50,
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    }
});

编辑:

查看道具时,样式似乎只是变成了一个指针:

children: {$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …}
src: "https://www.instagram.com/myinstagram"
style: 134
target: "_blank"

【问题讨论】:

  • 您可以从 props 中传递样式并在父组件中定义该样式。
  • @ShanAlam 我举了一个例子说明我是如何使用它导致错误的,你能澄清我做错了什么吗?
  • 样式应该在 {...this.props} 中不应该吗?
  • WebPseudoStyles.footerLinks 是一个有效的样式对象,对吧?
  • @wentjun 正确

标签: reactjs react-native react-native-web


【解决方案1】:

我刚刚将我的样式从 StyleSheet 对象转换为纯 JSON 对象。

export const WebPseudoStyles = {
    footerLinks: {
        color: footerTextColor,
        textDecoration: "none",
        fontFamily: fontFamily,
        marginBottom: 15
    },
    socialIcons: {
        textDecoration: "none",
        fontFamily: fontFamily,
    },
    socialIconsContainer: {
        backgroundColor: "#1e2234",
        paddingLeft: 10,
        paddingRight: 10,
        paddingTop: 10,
        paddingBottom: 10,
        marginLeft: 10,
        marginRight: 10,
        width: 50,
        height: 50,
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    }
};

此后,它不再是指针,而是实际的对象。

也许它不是“React-ish”,但它现在有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 2019-06-23
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多