javascript - 使用 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}
有什么解释吗??
解决方案
这不是特定于 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]
推荐阅读
- typescript - Nestjs - 如何从另一个服务获取可注入范围类型
- kubernetes - 具有端口转发的 Kubernetes 服务不进行负载均衡
- spring-boot - 在 https://jitpack.io 中找不到 com.fasterxml.jackson:jackson-bom:pom:2.9.6 被缓存在本地存储库中
- javascript - 如何在反应中按条件更改对象?
- python - 为什么分数显示不正确?
- python - Python 为什么 pd.to_datetime 返回时间戳格式?
- angular - 如果使用 es6 存在第二个数组,如何循环响应并连接数组
- linux - 登录服务器时拒绝访问
- javascript - fullcalendar 自定义按钮单击删除 html 元素
- video - 带透明背面的视频