pass id through on click react.js

前端 未结 6 1553
暖寄归人
暖寄归人 2020-12-08 16:52

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?

render(){
         


        
6条回答
  •  执笔经年
    2020-12-08 17:25

    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>
            
  • ) }) } render() { return ( < ul id = "todo" > { this.renderTodos() } < /ul> ) } } ReactDOM.render( , document.getElementById('react_example') );
    
    
    
    
      
      
      
    
    
    
      

提交回复
热议问题