Reactjs输入标记导致整个页面无法加载

chhkpiq4  于 2023-01-08  发布在  React
关注(0)|答案(1)|浏览(131)

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

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
h5qlskok

h5qlskok1#

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

const [name, setName] = useState('');
const [email, setEmail] = useState('');

或者,您可以在onChange事件中尝试类似以下内容:
这是针对名称输入事件处理程序的:

previousState => setName(previousState.target.value)

我还没有测试选项2,但理论上,它应该工作。

相关问题