【问题标题】:reactjs input tag causing the whole page to not loadreactjs 输入标签导致整个页面无法加载
【发布时间】:2023-01-08 03:03:40
【问题描述】:

所以,我正在学习 React Hooks,一切都很顺利,直到添加了标签,因为我通常会这样添加它:但是这导致整个页面崩溃但是以这种方式编写它,或者以通常的方式对制作的标签做出反应它再次工作。这背后有什么解释吗?

import React from 'react'
import { useState } from 'react'


function CounterHook() {
    const [count, Setcount] = useState(0)
    let [text, set_text] = useState("This is a Test TEXT")
    let [info , set_info] = useState({name:'', email:''})

 

    return (
    <div>
        <h3>{count}</h3>
        <button  onClick={() => Setcount(count + 1)} className='btn btn-primary'> Click </button>
        <h3> {text} </h3>

        <button  onClick={()=> set_text("The test Text has change nothing is the same anymore ")}  
        className='btn btn-success'> Change Me </button>
        <br />
        <br />
        
        <form>
            <input type="text" className={'form-control'} value={info.name}
         onChange={ event => set_info({name: event.target.value})} /> Enter your Name

        <input type={'text'} className={'form-control'} value={info.email} 
        onChange={ event => set_info({email: event.target.value})} /> Enter your Email
        
        {/* COMMENTED OUT CODE */} {/* that part of the code made the whole page blank */}
        {/* <input type="text" className={'form-control'} value={info.name}
         onChange={ event => set_info({name: event.target.value})}>  Enter your Name </input>

        <input type={'text'} className={'form-control'} value={info.email} 
        onChange={ event => set_info({email: event.target.value})}> Enter your Email </input> */}

        <h2> Name is: {info.name} </h2>
        <h2> Email is : {info.email} </h2>
        </form>
        
    </div>
  )
}

export default CounterHook
 

提前致谢。

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    因此,我立即想到的一个问题是 info 应该是一个具有以下形状的对象:{name:'', email:''} 但您将其设置为 {name:''} 或 {email:' '} 这将导致对象缺少对象道具之一。然后,您将尝试引用这两个道具,其中一个道具将根据您输入的内容而未定义。尝试为每个值设置两个独立的状态,如下所示:

    const [名称, 设置名称] = useState(''); const [email, setEmail] = useState('');

    或者你可以在你的 onChange 事件中尝试这样的事情:

    这是用于名称输入事件处理程序 (event)=> set_info(previousState=> {name:event.target.value, email:previousState.email})

    我还没有测试选项 2,但理论上它应该可以工作。希望这可以帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2022-01-17
      • 1970-01-01
      相关资源
      最近更新 更多