我想用反应组件中的任何内容替换不存在的图像。有没有办法我可以使用onError
以某种方式放置图像的位置?
render() {
return (
<img src={myImage} onError={(e)=>{/*Do something to replace the image with nothing*/}}/>
)
}
或者,我可以使用jquery来检测图像,如果没有找到,我只需要在return null
函数上使用render
。但就目前而言,我也无法做到这一点。这就是我的功能目前的样子:
checkIfImageExists () {
return $.get(myImage)
.done(() => console.warn('found it!', myImage))
.fail(() => console.warn('didnt fin it!', myImage))
}
render() {
console.warn(this.checkIfImageExists())
if (!this.checkIfImageExists().status) {
return null
}
return (
<img src={myImage}/>
)
}
这些问题是它永远找不到。我的代码有什么问题吗?如何修复它,以便在找不到图像时不渲染任何内容?
两种情况都需要使用组件state
异步处理图像:
state = { imgSrc: myImage } // depends on where myImage comes from
onImageError = () => {
this.setState({ imgSrc: null })
}
render() {
return (
{this.state.imgSrc && <img src={this.state.imgSrc} onError={this.onImageError }/>}
)
}
你可以使用CSS display: none
隐藏图像并显示它onload
:
class NonEmptyImage extends React.Component {
state = {
visible: false
}
handleLoad = _ => this.setState({ visible: true });
render() {
const { src } = this.props;
const { visible } = this.state;
return (
<img
src={src}
onLoad={this.handleLoad}
style={{ display: visible ? 'initial' : 'none' }}
/>
)
}
}
ReactDOM.render(<NonEmptyImage src='https://upload.wikimedia.org/wikipedia/en/thumb/4/4d/SpongeBob_SquarePants_characters_cast.png/300px-SpongeBob_SquarePants_characters_cast.png'/>, document.querySelector("#fw33f4w5"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="fw33f4w5"></div>
将src
改为随机的东西,你什么也看不见。
如果你讨厌这里的类的功能实例:
function NonEmptyImage({ src }) {
let ref;
return (
<img
ref={el => ref = el}
src={src}
onLoad={_ => ref.style.display = 'initial'}
style={{ display: 'none' }}
/>
)
}
ReactDOM.render(<NonEmptyImage src='https://upload.wikimedia.org/wikipedia/en/thumb/4/4d/SpongeBob_SquarePants_characters_cast.png/300px-SpongeBob_SquarePants_characters_cast.png' />, document.querySelector("#fw33f4w5ert"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="fw33f4w5ert"></div>