この質問には恥ずかしがりやがっかりするが、なぜ私はli要素にキーをバインドしようとすると、IcantはDOMをレンダリングした後にそれを見つけるのか分からない。コンソールで
React key cant要素に追加
<ul><br />
<li>I dont know why</li><br />
<li>cant find the key</li><br />
</ul><br />
:のように見えます 。
クリックイベントでe.target.getAttribute( 'key')を使用して '未定義'になりました。
ここに私のコード(シンプル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>
^うんを。あなたは、とにかく要素のキーで物事をしようとしてはいけません。リスト要素の一意の識別子が必要な場合は、自分で追加してください(ちょうど 'key'の名前を付けないでください) – Jayce444
私はこの部分を学び、前の鍵の意味を誤解していることが分かりました。ありがとう。レンダリングされたDOMには、文字列として設定されていても{}に置かれていても、自己定義属性のどれも見ることができません。それらはすべてReactによって破棄されましたか?seltを設定する必要があるか、定義する属性。 –
あなたが話している属性によって異なります。通常、ReactJSコンポーネントは、自己定義属性を必要とせずにほとんどのコモンシナリオを処理できます。 – mersocarlin