【发布时间】:2015-12-07 03:54:14
【问题描述】:
所以问题是我无法为我创建的按钮提供唯一的id。我当前提供id 的代码是每次调用组件时增加一个count 变量,然后将其分配给按钮,但所有按钮的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>
);
}
};
【问题讨论】:
-
旁注:请查看meta.stackoverflow.com/questions/260776/… 和meta.stackoverflow.com/questions/296391/… 了解添加随机问候是否是个好主意。
标签: javascript input reactjs