【问题标题】:react input field not updating useState with onClick event反应输入字段不使用 onClick 事件更新 useState
【发布时间】:2022-01-17 21:47:48
【问题描述】:

输入字段未更新城市 useState。 我也尝试过 onSubmit,但这导致了更多错误。有时当我按下提交按钮时,useEffect 会刷新整个页面。

    // using State for updating city 
    const [City, setCity] = useState();
// this function will fetch the data from Weather API, using useEffect 
    useEffect(() => {
        console.log("updating data" );
    }, [City] )
function CitySearch() {
        console.log(City);  
    }
                // taking input and updating the city, button using the city search function.
                // problem: city not updating !
    return (
       <div>
           <form>
                <input onClick={Event => setCity(Event.target.value)} placeholder="Enter city name"/>
                <button className="search-btn" type="submit" onClick={CitySearch} >Search</button>
           </form> 
        </div>

    )

【问题讨论】:

    标签: javascript reactjs event-handling use-effect use-state


    【解决方案1】:

    你应该在这里使用 onChange 来读取输入,onClick 用于点击处理。

                    <input onChange={Event => setCity(Event.target.value)} placeholder="Enter city name"/>
    

    为了停止重新加载表单提交,您可以在事件上使用 preventdefault ,不完全确定您在搜索提交调用 api 之后在做什么。

    【讨论】:

      【解决方案2】:

      试试这个:

        const [city, setCity] = useState("");
        // this function will fetch the data from Weather API, using useEffect
        const updateData = (event) => {
          let yourWrittenCityName = event.target.value;
          console.log(yourWrittenCityName);
      
          //update your data here from Api
        };
        const CitySearch = () => {
          console.log(city);
        };
      
        return (
          <div>
            <form>
              <input
                value={city}
                onChange={(e) => setCity(e.target.value)}
                onBlur={(e) => updateData(e)}
                placeholder="Enter city name"
              />
              <div onClick={CitySearch}>Search</div>
            </form>
          </div>
        );
      

      要更新输入值,您应该使用输入中的“value”属性和“onChange”函数。

      然后,当用户写完城市名称并离开输入时,您可以使用“onBlur”做一些事情。

      祝你好运?

      【讨论】:

        猜你喜欢
        • 2020-07-19
        • 1970-01-01
        • 2020-04-19
        • 2023-02-06
        • 1970-01-01
        • 2017-12-06
        • 2020-12-06
        • 1970-01-01
        • 2021-08-08
        相关资源
        最近更新 更多