简体   繁体   English

通过点击react.js传递id

[英]pass id through on click react.js

Below is my partial code but my question is very simple, how can I get says data-id="1" to my function when user clicked on the li ? 下面是我的部分代码,但我的问题很简单,当用户点击li时,我怎么能得到data-id =“1”到我的函数?

render(){
    return(
      <ul id="todo">
      {this.state.items.map((item,i) => 
        <li className='list-group-item' key={i} data-id={item.id}>{item.name}
        <button onClick={//how to pass item.id to my function?}>X</button>
        </li>
      )}
      </ul>
    ) 
  }

Since you are already using ES6 - might be a little cleaner to use an arrow function here: 由于您已经在使用ES6 - 在这里使用箭头功能可能会更清晰:

render(){
    return(
      <ul id="todo">
      {this.state.items.map((item,i) => 
        <li className='list-group-item' key={i} data-id={item.id}>{item.name}
        <button onClick={() => this.yourfunc(item.id)}>X</button>
        </li>
      )}
      </ul>
    ) 
}

You can use bind() to do this. 您可以使用bind()来执行此操作。

render(){
    return(
      <ul id="todo">
      {this.state.items.map((item,i) => 
        <li className='list-group-item' key={i} data-id={item.id}>{item.name}
        <button onClick={yourfunc.bind(this, item.id)}>X</button>
        </li>
      )}
      </ul>
    ) 
  }

Your function will receive item.id as the first parameter 您的函数将接收item.id作为第一个参数

You can do this as follows : 你可以这样做:

class Test extends React.Component {
    constructor(props){
         super(props);
         this.state = {
            items: [
                {item: "item", id: 1},
                {item1: "item1", id: 2}
            ]
         }
    }

    handleClick(id, e){
        alert(id);
    }

    render(){
        return(
           <ul id="todo">
               {this.state.items.map((item,i) => 
                    <li className='list-group-item' key={i} data-id={item.id}>{item.name}
                         <button onClick={this.handleClick.bind(this, item.id)}>X</button>
                    </li>
               )}
           </ul>
        ) 
   }
}

React.render(<Test />, document.getElementById('container'));

Here is jsfiddle . 这是jsfiddle

In my opinion, you shouldn't declare functions, nor bind methods within render method. 在我看来,你不应该声明函数,也不应该在render方法中绑定方法。 Neither of these: 这些都不是:

onClick={(e) => this.handleClick(e, item.id)}

onClick={this.handleClick.bind(this, item.id)}

I know it's plenty of tutoriales showing that syntax. 我知道有很多tutoriales显示语法。 But there's also a considerable number of blog posts warning about why that's not a good idea. 但也有相当多的博客帖子警告为什么这不是一个好主意。 Basically, you are creating a new function on each render. 基本上,您在每个渲染上创建一个新函数。

Go check the manual: https://reactjs.org/docs/handling-events.html 请查看手册: https//reactjs.org/docs/handling-events.html

And I'm aware that in the last two examples it does create functions on render . 我知道在最后两个例子中它确实在渲染上创建了函数 But react manual also shows this example and says: 但反应手册也显示了这个例子并说:

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

The problem with this syntax is that a different callback is created each time the LoggingButton renders. 此语法的问题是每次LoggingButton呈现时都会创建不同的回调。 In most cases, this is fine. 在大多数情况下,这很好。 However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. 但是,如果将此回调作为prop传递给较低组件,则这些组件可能会进行额外的重新呈现。 We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem. 我们通常建议在构造函数中使用绑定或使用类字段语法来避免这种性能问题。


BETTER SOLUTION 更好的解决方案

So, if you only need to pass one value, then check out the other examples in the manual. 因此,如果您只需传递一个值,请查看手册中的其他示例。 Basically you can bind the method in the constructor (or use an experimental syntax to avoid that step). 基本上,您可以在构造函数中绑定方法(或使用实验语法来避免该步骤)。

constructor(props) {
  super(props);
  this.handleClick = this.handleClick.bind(this);
}

And how would you get the id/value that you are trying to get? 你将如何得到你想要获得的id /值 See this example: 看这个例子:

 class App extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick({currentTarget}) { console.log(currentTarget.value) // e.currentTarget.value would be equivalent } render() { return ( <button value="here!" onClick={this.handleClick}> Click me </button> ); } } ReactDOM.render( <App />, document.getElementById('root') ); 
 body { padding: 5px; background-color: white; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

So, if you are using buttons or any form element (accepting a value ), you may definitively consider this syntax. 因此,如果您使用按钮或任何表单元素(接受 ),您可以明确地考虑这种语法。

Below is a running sample; 以下是正在运行的样本;

 class App extends React.Component { constructor(props) { super(props); this.state = { items: [{ id: 0, name: "Buy milk" }, { id: 1, name: "Write unit tests" }, { id: 2, name: "Cook a meal" }] } this.handleClick = this.handleClick.bind(this); } handleClick(value) { console.log(`${value} clicked`); } renderTodos() { return this.state.items.map((item, idx) => { return ( < li className = 'list-group-item' key = { idx } > { item.name } < button onClick = { () => this.handleClick(item.id) } > X < /button> </li > ) }) } render() { return ( < ul id = "todo" > { this.renderTodos() } < /ul> ) } } ReactDOM.render( <App/ > , document.getElementById('react_example') ); 
 <!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <meta charset="utf-8"> </head> <body> <div id="react_example"></div> </body> </html> 

Mayid is correct that it is not good to declare or bind functions in render method if the function is passed into other component as a props. Mayid是正确的,如果函数作为props传递给其他组件,则在render方法中声明或绑定函数是不对的。

Unfortunately currentTarget didn't work for me. 不幸的是,currentTarget并不适合我。

I have used getAttribute function of event.target. 我使用了event.target的getAttribute函数。 This doesn't cause unnecessary rerenders. 这不会导致不必要的重新渲染。

class App extends React.Component {
  handleClick = (event) => {    
    console.log(event.target.getAttribute('index'))
  }

  render() {
    return (
      <button index="1" onClick={this.handleClick}>   
        Click me
      </button>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM