【发布时间】:2018-07-11 00:09:41
【问题描述】:
我正在尝试编写一个反应组件,我可以在其中根据传递的道具加载不同样式的 div-s 并渲染它们。到目前为止,这是我的代码:
组件:
import React, { Component } from "react";
import s, { keyframes } from "styled-components";
import PropTypes from "prop-types";
import { jumpyRotation } from "../animations/jumpyRotation.js";
import { normalRotation } from "../animations/normalRotation.js";
import { baseShape } from "../shapes/base";
const animations = {
jumpyRotation: jumpyRotation,
normalRotation: normalRotation
};
const shapes = {
square: baseShape
};
class Loader extends Component {
render() {
const {
size = "14px",
color = "#000",
fontSize = "14px",
loaderText = "Loading...",
length = "4s",
animation = "jumpyRotation",
shape = "square"
} = this.props;
const styledShape = shapes[shape];
styledShape.attrs.size = size;
styledShape.attrs.color = color;
styledShape.attrs.animation = animation;
styledShape.attrs.length = length;
return (
<LoaderStyles
length={length}
animation={animations[animation]}
fontSize={fontSize}
color={color}
size={size}
>
styledShape
<span className="loader-text">{loaderText}</span>
</LoaderStyles>
);
}
}
Loader.propTypes = {
size: PropTypes.string, // Size in a valid CSS unit
color: PropTypes.string, // A valid CSS color, changes both loader and text
fontSize: PropTypes.string, // Size in a valid CSS unit
loaderText: PropTypes.string, // Text displayed under the loader
length: PropTypes.string, // The length of animation in a valid CSS unit
animation: PropTypes.string // The name of the animation
};
const LoaderStyles = s.div`
font-size: ${props => props.fontSize};
display: flex;
align-items: center;
justify-items: center;
flex-direction: column;
padding: ${props => props.fontSize};
.loader-text {
color: ${props => props.color};
}
`;
export default Loader;
样式化组件../shapes/base:
import s from "styled-components";
export const baseShape = s.div`
margin: ${props => props.size};
height: ${props => props.size};
width: ${props => props.size};
background-color: ${props => props.color};
animation: ${props => props.animation} ${props =>
props.length} linear infinite;
`;
现在根据styled component docs,使用语法应该可以工作,但我收到以下错误:
TypeError:无法设置未定义的属性“大小”
即使浏览器调试器将 styledShape 显示为 styled.div
【问题讨论】:
-
为什么你写了
import s,不应该是import styled,这是一个错字,因为我在API参考中没有找到任何s,而且这个错误意味着你的对象不包含名称为size的任何属性。这也表明您可能导入了错误的对象并试图访问这些不存在的属性。 -
@VinitRaj
importwithout{}只是为模块/包中的默认导出命名,它可以命名为任何你喜欢的名称,尽管我同意规范是 @987654331 @ -
是否可以从头开始定义属性?
const attrs = {size, color, animation, length};styledShape.attrs = {attrs} -
@cadmiun 试过
styledShape.attrs({ size, color, animation, length });,但获取 styledShape.attrs 不是一个函数。可能会尝试编写解决方法。 -
@MihaŠušteršič 在渲染块之前设置
const {...... //your content goes here} = this.props
标签: javascript reactjs styled-components