图片路径的确定
1. 静态资源
import React from 'react';
function App() {
return (
<img src={'/images/myImage.jpg'} alt="My Image" />
);
}
export default App;
2. 动态资源
import React from 'react';
function App() {
const imageSrc = require('./path/to/your/image.jpg');
return (
<img src={imageSrc} alt="My Image" />
);
}
export default App;
3. 使用CDN资源
function App() {
return (
<img src="https://cdn.example.com/path/to/image.jpg" alt="My Image" />
);
}
export default App;
动态改变src
属性
使用内联事件处理器
function App() {
const changeImage = () => {
const img = document.getElementById('myImage');
img.src = 'new-image.jpg';
};
return (
<>
<img id="myImage" src="initial.jpg" alt="Initial Image" onClick={changeImage} />
<button onClick={changeImage}>Change Image</button>
</>
);
}
export default App;
使用状态管理
import React, { useState } from 'react';
function App() {
const [imageSrc, setImageSrc] = useState('initial.jpg');
const changeImage = () => {
setImageSrc('new-image.jpg');
};
return (
<>
<img src={imageSrc} alt="My Image" />
<button onClick={changeImage}>Change Image</button>
</>
);
}
export default App;
图片加载失败的处理
import React from 'react';
function ImageComponent({ src, alt }) {
const handleImageError = (event) => {
event.target.onerror = null;
event.target.src = 'fallback-image.jpg';
};
return (
<img src={src} alt={alt} onError={handleImageError} />
);
}
export default ImageComponent;
总结