我正在尝试渲染图像。这是我的代码:
Accordion .jsx
import React from 'react';
import ArrowTemplate from "./ArrowTemplate";
function Accordion() {
return (
<div>
<ArrowTemplate arrowType={"BlackDown"} styles={""}/>
{/*<ArrowTemplate arrowType={"BlackUp"}/>*/}
{/*<ArrowTemplate arrowType={"WhiteDown"} styles={"background:black"}/>*/}
{/*<ArrowTemplate arrowType={"WhiteUp"} styles={"background:black"}/>*/}
</div>
);
}
export default Accordion;
ArrowTemplate.jsx
import BlackDownArrowSVG from './svgs/black-down-arrow.svg';
import WhiteDownArrowSVG from './svgs/white-down-arrow.svg';
import styled from 'styled-components';
import PropTypes from 'prop-types';
ArrowTemplate.propTypes = {
arrowType: PropTypes.string,
styles: PropTypes.string,
};
function ArrowTemplate(props) {
const {arrowType, styles} = props;
switch (arrowType) {
case "WhiteDown":
return (
styled.img.attrs({
src: WhiteDownArrowSVG,
})`${styles !== null ? styles : ""}`
);
case "BlackDown":
return (
styled.img.attrs({
src: BlackDownArrowSVG,
})`${styles !== null ? styles : ""}`
);
case "WhiteUp":
return (
styled.img.attrs({
src: WhiteDownArrowSVG,
})`transform: rotate(180deg); ${styles !== null ? styles : ""}`
);
case "BlackUp":
return (
styled.img.attrs({
src: BlackDownArrowSVG,
})`transform: rotate(180deg); ${styles !== null ? styles : ""}`
);
default:
throw("You need to pass arrowType");
}
}
export default ArrowTemplate;
SVG 路径正确。
作为我得到的错误:
Objects are not valid as a React child (found: object with keys {$$typeof, render, displayName, attrs, componentStyle, foldedComponentIds, styledComponentId, target, withComponent, warnTooManyClasses, toString}). If you meant to render a collection of children, use an array instead. in ArrowTemplate (at Accordion.jsx:7)
当我使用 console.log 时,我得到一个长对象。但是当我控制台记录来自 docs 的示例代码时,我得到了一个类似的对象。 :
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
//^^^^^^^^^^^^^^^^^^^^^
//This renders with no problem
我哪里出错了?
最佳答案
如果您在声明带样式的组件时遇到这种情况,您可能忘记了声明末尾的模板文字。所以
const AppContentWithSideBar = styled((props) => {
return (
<Wrapper>
<Router>
<SideBarWrapper>
<SideBar />
</SideBarWrapper>
<MainWrapper>
{props.children}
</MainWrapper>
</Router>
</Wrapper>
);
});
应该是
const AppContentWithSideBar = styled((props) => {
return (
<Wrapper>
<Router>
<SideBarWrapper>
<SideBar />
</SideBarWrapper>
<MainWrapper>
{props.children}
</MainWrapper>
</Router>
</Wrapper>
);
})``;
关于javascript - 对象作为具有样式化组件的 React 子项无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57569814/