Im이 새로운 질문에 부끄러워하지만 필자는 왜 li 요소에 키를 바인딩하려고 할 때 Icant가 DOM을 렌더링 한 후 그것을 찾지 못하는지 알지 못합니다. 콘솔
React key cant 요소에 더하기
<ul><br />
<li>I dont know why</li><br />
<li>cant find the key</li><br />
</ul><br />
:처럼 보이는 .
그리고 click 이벤트에서 e.target.getAttribute ('key')를 사용하여 'undefined'를 얻었습니다. 여기
내 코드 (간단하여 ToDoList) :
class Write extends React.Component {
constructor(props){
super(props);
this.handle=this.handle.bind(this);
}
handle(){
const text=document.getElementById('todoIn').value;
this.props.onWriteDown(text);
}
render(){
return (
<div>
<input type="text" id="todoIn" />
<button onClick={this.handle}>confirm</button>
</div>
);
}
}
class Todolist extends React.Component {
constructor (props) {
super(props);
this.n=0;
this.state={list:[]};
this.todolist=[];
this.handle=this.handle.bind(this);
this.handle_del=this.handle_del.bind(this);
}
handle (m) {
this.todolist.push({thing:m,vid:this.n++});
this.setState({list:this.todolist});
}
handle_del (e) {
var d = this.todolist.forEach((v,i)=>{
if(v.vid==e.target.getAttribute('key')){
return i;
}
});
this.todolist.splice(d,1);
this.setState({list:this.todolist});
}
render(){
var that = this;
var todo=[];
//here I create React Element for each todo and bind some attribute BUT ONLY CLICK EVENT is ACCESSIBLE.I JUST WONDER...
this.state.list.forEach(function(v,i,a){
let temp=<li key={v.vid.toString()} onClick={that.handle_del} >{v.thing}</li>;
todo.push(temp);
});
return(
<div>
<Write onWriteDown={this.handle} />
<ul>
{todo}
</ul>
</div>
);
}
}
ReactDOM.render(
<Todolist />,
document.getElementById('root')
);
<div id="root"></div>
^넵합니다. 어쨌든 요소의 키로 물건을 만들려고해서는 안됩니다. 목록 요소에 대한 고유 한 식별자를 원한다면 직접 추가하십시오. (단지 '키'라고 지칭하지 마십시오.) – Jayce444
이 부분을 배웠고 이전에 키의 의미를 잘못 이해했음을 알았습니다. 감사합니다. 렌더링 된 DOM에서 자기 정의 속성 중 어느 것도 문자열로 설정되거나 {}에 삽입 되더라도 상관 없습니다. 그들은 모두 React에 의해 폐기 되었습니까? selt를 설정해야하거나 원하는 경우 어떻게 할 수 있습니까? 정의 속성. –
당신이 말하는 속성에 달려 있습니다. 일반적으로 ReactJS 구성 요소는 자체 정의 속성이 없어도 대부분의 공유 시나리오를 처리 할 수 있습니다. – mersocarlin