【问题标题】:dot Notation vs bracket notation with Reactjs使用 Reactjs 的点表示法与括号表示法
【发布时间】:2020-05-17 05:38:06
【问题描述】:

我有一个表单和表单状态的表单元素的更改处理程序,问题是当按下表单的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:''
            },

        }})

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

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

有什么解释吗??

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这不是 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]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多