Reactjs 如何将图像src添加到react state和setstate

Reactjs 如何将图像src添加到react state和setstate,reactjs,setstate,react-state-management,imgsource,Reactjs,Setstate,React State Management,Imgsource,我正在制作一个应用程序,它需要将上的handleChange传递给州政府 import React, { Component } from 'react' export class App extends Component { render() {         const selectCountryChange = () => {             const img = document.querySelector('#img-country');  

我正在制作一个应用程序,它需要将
上的
handleChange
传递给州政府

 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
import React,{Component}来自“React”
导出类应用程序扩展组件{
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\`;
        };  
报税表(
印度
我们
英国
            
              
        )  
    }  
}  
导出默认应用程序

任何人都可以告诉我如何添加状态管理以对
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;
导出类应用程序扩展组件{
陈述={
imageSrc:“”,
imageAlt:'
}
手变(e){
const countryCode=e.target.getAttribute('data-countryCode').toLowerCase()
这是我的国家({
imageSrc:'https://flagpedia.net/data/flags/h80/“+countryCode+”.webp',
imageAlt:countryCode
})
}
render(){
报税表(
印度
我们
英国
)  
}  
}  
导出默认应用程序;

选择CountryChange
中更改国家/地区时,您希望图像源更改吗?是的,我希望图像源在您更改国家/地区时更改,并将img.src传递给州好的,我想有人发布了一个问题,该问题引用了您刚才告诉我的内容。看看是否有帮助。