【问题标题】:How to provide a different id for each component creating a button is called如何为创建按钮的每个组件提供不同的 id 称为
【发布时间】: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>
    );
  }
};

【问题讨论】:

标签: javascript input reactjs


【解决方案1】:

比起传递 todo 的 ID,我更倾向于传递一个 remove 方法作为 prop,而 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} />

【讨论】:

  • 感谢您的回答:D,由于您的回答,我了解到方法也可以作为道具传递,我认为值是唯一可以传递的 XD
【解决方案2】:

不太确定您需要 id 做什么,但是当您执行 map 时,也只需传递迭代器,这样您就会得到类似的东西

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

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

【讨论】:

  • 感谢您的回答:D
猜你喜欢
  • 2020-06-13
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多