Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React key cant add to element

Tags:

reactjs

key

Im new to React and feeling shy to ask this question,but I dont know why that when I try to bind key to li element,Icant find it after rendering DOM. Which looks like:

<ul><br />
  <li>I dont know why</li><br />
  <li>cant find the key</li><br />
</ul><br />

in console.
And I got 'undefined' with e.target.getAttribute('key') in click event.
Here my code (a simple 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>
like image 359
沈江平 Avatar asked Dec 03 '25 07:12

沈江平


1 Answers

key is used internally so React knows which components have been added, changed or removed. Also, keys don't get passed through.

For more information check ReactJS's doc.

https://facebook.github.io/react/docs/lists-and-keys.html#keys

like image 82
mersocarlin Avatar answered Dec 06 '25 01:12

mersocarlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!