首页 > 解决方案 > 使用 Reactjs 的点表示法与括号表示法

问题描述

我有一个表单和表单状态的表单元素的更改处理程序,问题是当按下表单的div时创建更多元素输入,请检查以下changeHandler。

国家:

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:''
            },

        }})

变更处理程序:

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})
}

以下是将对象转换为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}/>
))

经过调试,我发现不是以括号表示法的格式调用对象元素,而是用点表示法调用它:

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

有什么解释吗??

标签: javascriptreactjs

解决方案


这不是特定于 React,这只是一个 javascript 问题。

还有这些:

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

不是一回事。

const new_ele_config = {...new_controls['ele']}将与
const new_ele_config = {...new_controls.ele}

因为括号表示法允许动态引用,所以ele没有引号被视为一个变量,而使用点表示法它总是被视为一个字符串。

出于同样的原因,你不能用 Array.0 代替 Array[0]


推荐阅读