當我單擊類組件中的按鈕時,我希望影像發生變化。我知道函陣列件,但我該怎么做?
class Coffies extends React.Component{
constructor(props){
super(props)
this.state={
giphy:[],
loading:false
}
}
componentDidMount(){
const apiURL = "https://api.giphy.com/v1/gifs/random";
const apiKEY = "bi3FFnNepwMz5HlDYwCfvyhXQLGrvVtL";
const randomIndex = Math.floor(Math.random()*50);
axios(`${apiURL}?api_key=${apiKEY}`)
.then((response)=> this.setState({
giphy : response.data.data.images.fixed_height.url,
loading: true
}))
}
render(){
return (
<>
<img
className="cats-img"
src={this.state.giphy}
alt="Loading.."
/>
<button onClick={()=> this.setState({loading : false})} className="mt-5 py-3 btn generate-btn">
Get Random Cat Images
</button>
</>
)
}
}
export default Coffies ;
uj5u.com熱心網友回復:
如果創建方法,則可以通過單擊按鈕更改影像 changeImage
changeImage = () => {
this.setState({
loading: true,
});
this.getImage();
};
現場演示
并呼叫其中的getImage方法
getImage() {
const apiURL = "https://api.giphy.com/v1/gifs/random";
const apiKEY = "bi3FFnNepwMz5HlDYwCfvyhXQLGrvVtL";
axios(`${apiURL}?api_key=${apiKEY}`).then((response) => {
this.setState({
giphy: response.data.data.images.fixed_height.url,
loading: false,
});
});
}
uj5u.com熱心網友回復:
ComponentDidMount()通常只運行一次,因此它不是放置影像加載邏輯的好地方。您應該將您的邏輯放在 onClick 處理程式中:
<button onClick={changeImage} className="mt-5 py-3 btn generate-btn">Get Random Cat Images</button>
然后呼叫@decpk 建議的函式
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/369623.html
標籤:javascript 反应
