所以問題是我無法設法爲我創建的按鈕提供唯一的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>
);
}
};
邊注:請檢查http://meta.stackoverflow.com/questions/260776/should-i-remove-fluff-when-editing-questions和http://meta.stackoverflow.com/問題/ 296391 /應該 - 短語 - 這樣 - 我 - 我 - 是新增的x被編輯 - 問題是否增加隨機問候是好主意。 –