下面的代码是一个双向绑定
反应
,而只有一种类型,文本和输入值同时更新。
下面是组件循环:
if (this.state.personState){
persons = (
<div>
{this.state.person.map( (person, index) =>{
return
<Person
click = {()=>this.deletePerson(index)}
name = {person.name}
age = {person.age}
key = {person.id}
changed = { (event)=>this.changeNameHandler(event, person.id)} >
</Person>
})}
</div>
)
处理事件的函数
changeNameHandler = (event, id) => {
const personIndex = this.state.person.findIndex(person => person === id)
// making a copy and not manipulating the original reference
const personcpy = { ...this.state.person[personIndex] }
// assign the value of the event target
personcpy.name = event.target.value;
// making a copy of the state to update the dom
const persons = [...this.state.person]
// updating...
persons[personIndex] = personcpy
// state update
this.setState({ persons : persons })
}
javascript对象本身
state = {
person : [
{id:'12121', name:"Jimmy", age:12},
{id:'121s', name:"Jack", age:15},
{id:'23232a', name:"pouya", age:27}
]
}
部件代码
const Person = (props) => {
return (
<div className="Person" >
<p onClick={props.click}>I'm {props.name} and I'm {props.age} years old</p>
<input onChange={props.changed} value={props.name} />
<h1 >{props.name}</h1>
</div>
)
}
我知道
查找索引()
返回数组中满足给定测试的第一个元素的索引。
我正在测试更改时事件的索引是否与对象索引相同!
但是,这不起作用,当我试着打字的时候,它就冻结了
我已经检查了chrom的开发工具并尝试在那里进行调试,似乎有一个引用错误!但我不明白!怎么会这样?
请帮助我从不同的角度看问题。