reactjs - 如何在反应中使用onload?
问题描述
要运行 imagesrore 函数 onload 我必须调用<img src="image_7.jpg" className="hide" alt="image_7.jpg"/>
image 但实际上没有使用此行,如果我删除此 onload 将不起作用并且不会调用函数。那么如何在反应中调用 imagestore() onload。
class PicturesList extends React.Component {
constructor(props) {
super(props);
this.state = {
imagesarray: []
};
this.imagestore = this.imagestore.bind(this);
}
render() {
return (
<div>
<div onLoad= {() => this.imagestore()}>
<img src="image_7.jpg" className="hide" alt="image_7.jpg"/>
// To run the imagesrore function onload I have to call this image but actually there is no use of this line and if I remove this onload doesn't work and function is not called
</div>
<Gallery url={this.state.imagesarray}/>
</div>
);
}
imagestore()
{
const imgUrls=this.props.apikeys;
const objarr = Object.values(imgUrls);
this.setState({
imagesarray: objarr
});
}
}
我想要的是
class PicturesList extends React.Component {
constructor(props) {
super(props);
this.state = {
imagesarray: []
};
this.imagestore = this.imagestore.bind(this);
}
render() {
return (
<div>
<div onLoad= {() => this.imagestore()}>
// but when I did this imagestore() function not called
</div>
<Gallery url={this.state.imagesarray}/>
</div>
);
}
imagestore()
{
const imgUrls=this.props.apikeys;
const objarr = Object.values(imgUrls);
this.setState({
imagesarray: objarr
});
}
}
解决方案
您可以简单地将其加载到 componentDidMount 中,而不是渲染您不想要的图像
class PicturesList extends React.Component {
constructor(props) {
super(props);
this.state = {
imagesarray: []
};
this.imagestore = this.imagestore.bind(this);
}
componentDidMount() {
const img = new Image();
img.onload =() => {
// image has been loaded
this.imagestore()
};
img.src = 'image_7.jpg';
}
render() {
return (
<div>
</div>
<Gallery url={this.state.imagesarray}/>
</div>
);
}
imagestore() {
const imgUrls=this.props.apikeys;
const objarr = Object.values(imgUrls);
this.setState({
imagesarray: objarr
});
}
}
上述解决方案只是在加载图像后调用 imageStore。但是,如果您打算在组件完全加载时调用 imageStore,只需this.imageStore()
在 componentDidMount 中触发
class PicturesList extends React.Component {
constructor(props) {
super(props);
this.state = {
imagesarray: []
};
this.imagestore = this.imagestore.bind(this);
}
componentDidMount() {
this.imagestore()
}
render() {
return (
<div>
</div>
<Gallery url={this.state.imagesarray}/>
</div>
);
}
imagestore() {
const imgUrls=this.props.apikeys;
const objarr = Object.values(imgUrls);
this.setState({
imagesarray: objarr
});
}
}
推荐阅读
- visual-studio-2017 - Visual Studio 2017 失去智能感知
- c# - C# 单元测试在将图像保存到服务器时失败,但应用程序工作正常
- python-3.x - 在 Pandas 中使用 unstack
- java - JPA 不同的内部联接与联接表上的条件
- asp.net - 如何动态地将行添加到我的表中并回发数据以查看
- python - 如何使用尚未声明的类的类型注释函数?
- docker - 设置 docker-compose 以观察多包 golang 项目的变化
- javascript - 从数组返回值时获取未定义 - Node JS
- javascript - 从角度组件将对象传递给自定义装饰器
- spring - Spring-webflux,如何在@ExceptionHandler 中获取请求作为参数