代码之家  ›  专栏  ›  技术社区  ›  cjm2671

如何在React中使用按钮传递ID?

  •  0
  • cjm2671  · 技术社区  · 7 年前

    DELETE 请求服务器。我在挣扎的是, handleDelete() ?

    import React from 'react';
    import client from '../../api/';
    import { Button } from 'reactstrap'
    class Post extends React.Component {
    
    
      constructor(props) {
        super(props)
        this.id = props.id
      }
    
      handleDelete(event) {
        console.log(event);
        alert(event.id);
        event.preventDefault()
        }
    
        render() {
          return (
            <div>
              <h1>Title: {this.props.title} {this.props.id}</h1>
              <p>{this.props.body}</p>
              <Button id={this.props.id} onClick={this.handleDelete} color="danger">Delete</Button>
            </div>
          )}
    }
    
    export default Post
    
    3 回复  |  直到 7 年前
        1
  •  0
  •   xehpuk    7 年前

    这应该可以做到:

    constructor(props) {
      super(props)
      this.handleDelete = this.handleDelete.bind(this)
    }
    
    handleDelete(event) {
      console.log(event)
      alert(this.props.id)
      event.preventDefault()
    }
    
        2
  •  0
  •   Igor Alemasow    7 年前

    使用this.props.id和rewrite handledelite函数以及arrow函数保存组件上下文

    handleDelete=(event) => {
        console.log(event);
        alert(this.props.id);//here is post id
        event.preventDefault()
    }
    
        3
  •  0
  •   Dmitriy    7 年前

    <Button id={this.props.id} onClick={() => this.handleDelete(this.props.id)} color="danger">Delete</Button>