![](/img/trans.png)
[英]React.js child component not updating styling derived from props, why? (styled-components)
[英]Styled-components in React.js - props doesn't work
我什么都试过了。 至少,有一段时间,我找不到任何新的可能解决我的问题的方法。 有可能我不明白某些东西,因为我正处于 React.js 冒险的开始。
重点:
我想创建一个带有背景图像的组件标题。 在父组件中,我将图像 URL 作为道具,并尝试在子组件中将其用作background-image: URL()
。 当然,它不起作用。 另外,我尝试设置颜色,但它也不起作用。
这是我的父组件:
import Hero from '../Hero';
import image from './cat.jpg'
function Main() {
return <div>
<Hero title="Only fluff photos" image={image} color="#f0f"/>
</div>
};
这是我的子组件:
import styled from 'styled-components';
const StyledHeader = styled.header`
display: flex;
width: 100%;
height: 432px;
background-image: url(${(props) => props.image});
background-color: ${props => props.color ? props.color : "#ff0"};
`
function Hero(props) {
return <StyledHeader>
<h1>{props.title}</h1>
<img src={props.image} alt="test cat" />
</StyledHeader>
};
我试过的:
src
放入 img 标签 - 它可以工作{image}
中导入 img - 它可以工作require()
- 它不起作用url(~{props.image})
- 它不起作用StyledHeader
道具 - 它不起作用当然,从 3 到 6 的所有点都不起作用,因为没有任何道具起作用。 但后来我发现了。
styled-components 给出了一个 props 使用的例子:
background: ${props => props.primary ? "palevioletred" : "white"};
它对我没有帮助:(
提前感谢您的帮助。 我不知道我做错了什么。
它不起作用,因为您必须为 Styled header 提供如下道具
const StyledHeader = styled.header`
display: flex;
width: 100%;
height: 432px;
background-image: url(${(props) => props.image});
background-color: ${props => props.color ? props.color : "#ff0"};
`
function Hero(props) {
return <StyledHeader image={props.image} color={"value"} {...otherProps}>
<h1>{props.title}</h1>
<img src={props.image} alt="test cat" />
</StyledHeader>
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.