简体   繁体   English

使用 Reactjs 的点表示法与括号表示法

[英]dot Notation vs bracket notation with Reactjs

I have a change Handler for a form and Form elements in the form of state, the issue is when pressing on the div of the form of more element input is created, please check the following changeHandler.我有一个表单和表单元素的更改处理程序,形式为 state,问题是在创建更多元素输入的表单的 div 时,请检查以下更改处理程序。

the State: State:

const [InputState,setInputstate]=useState(
    {
        controls: {
            email: {
                elementType:'input',
                elementConfig:{
                    type:'email',
                    placeholder:'Enter Your Email'
                },
                value:''
            },
            password: {
                elementType:'input',
                elementConfig:{
                    type:'password',
                    placeholder:'Enter Your password'
                },
                value:''
            },

        }})

The changeHandler:变更处理程序:

const ChangeHandler=(event,ele)=>{
    const new_controls = {...InputState.controls}
    const new_ele_config = {...new_controls[ele]}
    new_ele_config.value = event.target.value
    new_controls[ele] = new_ele_config
    setInputstate({controls: new_controls})
}

The following is to transform the object into an Array to return Input component:下面是将 object 转换为 Array 以返回 Input 组件:

let FormElements = []
for (let ele in InputState.controls){
    FormElements.push({
        ele:ele,
        config:InputState.controls[ele]
    })
}
let Form =null
Form =FormElements.map((ele,index)=>(
    <Input key={index}
        changed={(event)=>ChangeHandler(event,ele.ele)}
        elementconfig={ele.config.elementConfig}/>
))

After debugging, I discovered that instead of calling the object element in the format of bracket notation I called it with dot notation:经过调试,我发现不是以括号表示法的格式调用 object 元素,而是用点表示法调用它:

const new_ele_config = {...new_controls[ele]} 
const new_ele_config = {...new_controls.ele}

Any explanation??有什么解释吗??

This isn't specific to React, this is just a javascript question.这不是特定于 React,这只是一个 javascript 问题。

and these:还有这些:

const new_ele_config = {...new_controls[ele]} 
const new_ele_config = {...new_controls.ele}

are NOT the same thing.不是一回事。

const new_ele_config = {...new_controls['ele']} would be the same as const new_ele_config = {...new_controls['ele']}将与
const new_ele_config = {...new_controls.ele}

Because bracket notation allows for dynamic references, so ele without quotes is seen as a variable, while with dot notation it's always seen as a string.因为括号表示法允许动态引用,所以不带引号的ele被视为变量,而使用点表示法时,它始终被视为字符串。

For the same reason you can't do Array.0 instead of Array[0]出于同样的原因,你不能用 Array.0 代替 Array[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM