我正在使用 SlateJS,我需要延迟 <img src={imgSrc} />
的返回直到imgSrc
是一个定义的值(它从 blob 中作为 DataURL 读取)
有什么办法可以做到这一点吗?
我知道这不起作用(而且这是不明智的),但理论上我可以做一些类似的事情:
return setTimeout(function() {return <img src={imgSrc} />, 1000)
最佳答案
如果您想在定义图像的值后立即渲染图像,请尝试以下操作:
方法 1:使用采用 imgSrc 属性的高阶函数,如下所示 <ImageComponent imgSrc={} />
const ImageComponent = ({ imgSrc }) => {
if (!imgSrc) {
return <span></span>
} else {
return <img src={imgSrc} />
}
}
方法 2:在运行 return 语句的位置渲染一些内联代码。
{ this.props.imgSrc && <img src={imgSrc} />}
上面的代码非常酷,它的作用是如果定义了 imgSrc 属性则渲染 img 元素,否则它什么也不做。它是 react 性的,因此当 imgSrc 更改时,元素会重新渲染。
希望有帮助。
关于javascript - 只有在某个条件成立后才在 React 中返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654057/