[英]Why I can't display my images in react.js
我试图在我的页面上显示两个 svg 图像以做出反应,但它不起作用,你知道为什么吗?
这是 manifest.json 文件:
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "stone_black.svg",
"sizes": "64x64",
"type": "image/svg+xml"
},
{
"src": "stone_white.svg",
"sizes": "64x64",
"type": "image/svg+xml"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
这是我实现它的地方:
function Square(props) {
// Elements that will display the game stones
var srcToDisplay = ""
if (props.value === "white") {
srcToDisplay = "public/stone_white.svg"
} else if (props.value === "black") {
srcToDisplay = "public/stone_black.svg"
} else {
srcToDisplay = ""
}
return (
<button
className="squares"
onClick={props.onClick}>
<img src={srcToDisplay} />
</button>
)
}
提前非常感谢:)
在 React 中使用图像时,一般规则是将图像导入组件中。 我不知道你设置的细节,但如果你使用大多数标准的 React 设置,你应该使用这样的东西:
import stone_white from 'public/stone_white.svg'; // The relative path to the image
import stone_black from 'public/stone_black.svg';
function Square(props) {
// Elements that will display the game stones
if (props.value === "white") {
srcToDisplay = stone_white;
} else if (props.value === "black") {
srcToDisplay = stone_black;
} else {
srcToDisplay = ""
}
return (
<button
className="squares"
onClick={props.onClick}>
<img src={srcToDisplay} />
</button>
)
}
此外,您可能不想从public
目录中获取图像。 您可能需要考虑将图像存储在src
文件夹中的专用目录中。
尝试功能,为此
function Square(props) {
// Elements that will display the game stones
var srcToDisplay = ""
const handlerOnClick = () => {
if (props.value === "white") {
srcToDisplay = "public/stone_white.svg"
} else if (props.value === "black") {
srcToDisplay = "public/stone_black.svg"
} else {
srcToDisplay = ""
}
}
return (
<button
className="squares"
onClick={()=> handlerOnClick()}>
<img src={srcToDisplay} />
</button>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.