2015-12-07 22 views
0

所以問題是我無法設法爲我創建的按鈕提供唯一的id。我當前提供的id的代碼是每次調用該組件時增加一個count變量,然後將其分配給按鈕,但所有按鈕的id總是以當前計數結束。我將使用id作爲刪除數組中特定元素的基礎。任何其他方法將不勝感激。如何爲每個創建按鈕的組件提供不同的ID號碼

下面是一個創建按鈕組件:

class TodoListItem extends React.Component { 
    constructor(props) { 
    super(props); 
    this.onDelete = this.onDelete.bind(this); 
    this.arrTodos = this.props.todos; 
    } 
    onDelete(e) { 
    let btnDel = ReactDOM.findDOMNode(this.refs.btnDel); 
    } 
    render() { 
    return (
     <div> 
     <li> 
      {this.props.desc} 
      <span> </span> 
      <input ref="btnDel" type='submit' id={this.props.btnID} value='Delete' onClick={this.onDelete} /> 
     </li> 
     </div> 
    ); 
    } 
} 

而這裏的主類:

class Todolist extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     todos: [], 
     btnID: -1 
    }; 
    this.onSubmit = this.onSubmit.bind(this); 
    this.createTodo = this.createTodo.bind(this); 
    this.todos = {}; 
    this.todoID = 0; 
    } 
    onSubmit(e) { 
    let value = this.refs.myInput.value; 
    let myInput = ReactDOM.findDOMNode(this.refs.myInput); 
    if (value == "") { 
     myInput.focus(); 
     return; 
    } else { 
     let newTodo = { 
     idTodo: this.todoID, 
     desc: value, 
     done: false 
     }; 
     this.todos = newTodo; 
     this.setState({ 
     todos:[...this.state.todos,newTodo], 
     btnID: this.state.btnID + 1 
     }); 
     myInput.value = ""; 
     myInput.focus(); 
     this.todoID++; 
    } 
    } 
    onInput(e) { 
    this.setState({text: e.target.value}); 
    } 
    createTodo(todo) { 
    return <TodoListItem key={todo.idTodo} todos={this.state.todos} desc={todo.desc} btnID={this.state.btnID} /> 
    } 
    render() { 
    return(
     <div> 
     <input ref="myInput" placeholder="What To Do?" /> 
     <input type="submit" onClick = {this.onSubmit} /> 
     <ul>{this.state.todos.map(this.createTodo)} </ul> 
     </div> 
    ); 
    } 
}; 
+0

邊注:請檢查http://meta.stackoverflow.com/questions/260776/should-i-remove-fluff-when-editing-questions和http://meta.stackoverflow.com/問題/ 296391 /應該 - 短語 - 這樣 - 我 - 我 - 是新增的x被編輯 - 問題是否增加隨機問候是好主意。 –

回答

0

與傳遞todo的ID不同,我會試圖通過remove方法作爲道具,而todo已經綁定到位。

removeTodo: function(target) { 
    const { todos } = this.state; 

    this.setState({ 
    todos: todos.filter(todo => todo !== target) 
    }); 
} 

然後,您可以部分應用要傳遞給組件的函數版本。

createTodo(todo) { 
    const remove = this.removeTodo.bind(this, todo); 

    return <TodoListItem key={todo.idTodo} todos={this.state.todos} desc={todo.desc} remove={remove} /> 
} 

然後在你的組件中,當你想刪除它時,你可以簡單地調用remove函數。

<input type='submit' value='Delete' onClick={this.props.remove} /> 
+0

感謝您的回答:D,並且由於您的回答,我已經瞭解到方法也可以作爲道具傳遞,我認爲值是唯一可以傳遞的XD – Swellar

0

不能確定你所需要的ID,但是當你做你的map剛及格迭代器,所以你會有類似的東西

this.state.todos.map(function(todo, i){ 
    this.createTodo(todo, i); 
}.bind(this)); 

然後在您的createTodo中,您可以使用i作爲您的key和您的id

+0

感謝您的回答:D – Swellar

相關問題