首页 > 解决方案 > 我如何在 React js 的 div 中更改我的 background_image

问题描述

我做了一个气象应用程序,我想改变我所在城市的背景。

我的问题是我可以使用经典的 cssfile 进行更改,例如:


body {
  font-family: 'montseratt', sans-serif;
  background-color:white;
  background-image: url('./assets/paris.jpg');
  background-repeat:repeat;

}

但是当我将它退休并尝试在这样的 div 中它不起作用时:

    <div style={{background_image: 'url(./assets/paris.jpg)'}}>

我不明白为什么。

有我的全部代码,但我认为它没有用

function Accueil()
{

  
  const [query, setQuery] = useState('');
  const [weather, setWeather] = useState({});
  const [time, setTime] = useState(Date.now());
  const [city, setCity] = useState('')
  const [fond, setFond] = useState((''))
  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    const interval = setInterval(() => setTime(new Date().toLocaleString()), 1000);
    return () => {
      
      clearInterval(interval);
    };
  }, []);
  
   const sendtemp = (props) => {
    fetch('getmeteo/?city=' + props) 
    .then((response) => response.json())
    .then((responseData) => {
      responseData.temp -= 273.15
      responseData.temp = responseData.temp.toFixed(2)
      responseData.temp = responseData.temp + "°C"
      setWeather(responseData);
      const pro = props.toLowerCase()
      setFond("./assets/" + pro + ".jpg")
      const pop = pro.charAt(0).toUpperCase() + pro.substring(1)

      setCity(pop)
      setQuery('')
    })
  }
  const search = evt => {
    if (evt.key === "Enter"){
      setQuery('')
      sendtemp(query);

    }
  }

  
  return (
    <div style={{background_image: 'url(./assets/paris.jpg)'}}>

      

<main>
      
        <div className="search-box">
          <input
          type="text"
          className="search-bar"
          placeholder="Search..."
        
          onChange={e =>setQuery(e.target.value)}
          value = {query}
          onKeyPress={search}
          />
          
        </div>
              <div className="location">
              {(time)}
        </div>
        {weather.temp ? (
       <div className="weather-box">
        
       {weather.temp}
         </div>
      ) : ( <div></div>)}
        
        <div className="location">
            {city}
        </div>

        </main>
   
    <div>
      
    </div>
    </div>
    
  
  );
}

谢谢你的回答

标签: javascriptreactjs

解决方案


** 更改响应

查看代码,没有理由使用花括号,因为没有动态呈现任何内容。我想它应该和标准的 HTML 元素一样写。

 <div style="background_image: url(./assets/paris.jpg)">

推荐阅读