我有一个API调用,可检索如下所示的对象数组 {id:12313,isComplete:true}
changeImage(isComplete: string) {
let image = document.getElementById("icon-status") as HTMLImageElement
if(isComplete) {
return image.src = '../ClientApp/images/Green.png'
}
return image.src = "../ClientApp/images/Grey.png";
}
如果isComplete = true,则基本设置image.src =“绿色”,否则设置image.src =“灰色”
我的HTML看起来像这样<img src={this.changeImage(task.isComplete)} width="22" alt="" className="icon" id="icon-status"/>
此刻我遇到TypeError:无法将属性'src'设置为null。.
有什么想法吗?
答案 0 :(得分:2)
您可以尝试将task.isComplete
与三元运算符结合使用,以为img元素提供正确的src
。而不是尝试在DOM中操作img元素。
<img
src={
task.isComplete
? "../ClientApp/images/Green.png"
: "../ClientApp/images/Grey.png"
}
width="22"
alt=""
className="icon"
id="icon-status"
/>
答案 1 :(得分:0)
const [image, setImage] = useState()
useEffect(() => {
if (isComplete) {
setImage(require('../ClientApp/images/Green.png'))
} else {
setImage(require('../ClientApp/images/Gray.png')
}
}, [image])
<img
src={image}
width="22"
alt=""
className="icon"
id="icon-status"
/>