我想使用来自其父级的 react props 加载图像,但我无法使用 props 加载图像。该页面为空白,其他字段如图像标题和 div 中的按钮可见,但图像为空。 我正在使用 evergreen-ui 进行造型。 父类:
class Trending extends Component {
constructor() {
super();
this.state = {
images: [
{
id: "1",
img_name: "liverpool-1",
heading: "Nike Football Impulse Pack",
},
{
id: "1",
img_name: "shoe-1",
heading: "Nike Football Impulse Pack",
},
],
};
}
render() {
return (
<Pane>
<Pane>
<Heading
size={1400}
color="#111"
marginLeft={20}
marginRight={20}
paddingTop={10}
paddingBottom={20}
fontWeight={500}
fontFamily="Helvetica Neue|Helvetica|Arial|sans-serif">
Trending
</Heading>
<Pane
display="flex"
position="relative"
marginLeft={20}
marginRight={20}>
{this.state.images.map((image) => (
<ImageButton
id={image.id}
img_name={image.img_name}
heading={image.heading}
/>
))}
</Pane>
</Pane>
</Pane>
);
}
}
导出默认趋势;
子类:
class ImageButton extends Component {
constructor(props) {
super(props);
this.state = {
images: [
{
img_name: "",
heading: "",
},
],
};
}
render() {
return (
<Pane className="img-container" marginRight={5}>
<img
src={require("../assets/images/" + this.props.img_name + ".png")}
alt=""
/>
<Pane className="btn-txt">
<Heading size={600} className="txt">
{this.props.heading}
</Heading>
<Button className="btn"> Shop </Button>
</Pane>
</Pane>
);
} }
导出默认的ImageButton;
答案 0 :(得分:0)
来自 create-react-app 网站的示例
import React from 'react';
import logo from './logo.png';
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
}
export default Header;
如果您的图像中有条件,请使用字符串插值。
<img src={`../assets/images/`${this.props.img_name}.png`)}/>
还要确保检查图像的相对路径。