如何将image src添加到react state和setstate中



我正在制作一个应用程序,该应用程序必须要求在<img/>标签上传递handleChange,以将image.src存储到状态

import React, { Component } from 'react'  
export class App extends Component {  
render() {  
        const selectCountryChange = () => {  
            const img = document.querySelector('#img-country');  
            const select = document.querySelector('#country');  
            img.src = `https://flagpedia.net/data/flags/h80/${select.selectedOptions[0].dataset.countrycode.toLowerCase()}.webp`;  
        };  
        return (  
<div>  
<select id="country">  
<option data-countryCode="IN" value="91">India</option>  
<option data-countryCode="US" value="1">US</option>  
<option data-countryCode="GB" value="44">UK</option>  
</select>  

<div class="image">  
<img src="" id="img-change">  
          </div>  
            </div>  
        )  
    }  
}  
export default App

有人能告诉我如何添加状态管理来对img.src做出反应吗

当选择国家/地区时,您可以使用select的onChange事件来更改组件的状态。

export class App extends Component {  
state={
imageSrc:'',
imageAlt:''
}
handleChange(e){
const countryCode=e.target.getAttribute('data-countryCode').toLowerCase()
this.setState({
imageSrc:'https://flagpedia.net/data/flags/h80/'+countryCode+'.webp',
imageAlt:countryCode
})
}
render() {  
return (  
<div>  
<select id="country" onChange={this.handleChange}>  
<option data-countryCode="IN" value="91">India</option>  
<option data-countryCode="US" value="1">US</option>  
<option data-countryCode="GB" value="44">UK</option>  
</select>  

<div class="image">  
<img src={this.state.imageSrc} id="img-change" alt={this.state.imageAlt}/>  
</div>  
</div>  
)  
}  
}  
export default App;

最新更新