编辑列表中的特定元素以响应打字稿

时间:2019-07-15 15:50:39

标签: reactjs typescript function react-native binding

我正在创建一个具有响应的项目​​列表,该项目具有在后台运行的“编辑”和“删除”按钮。我现在正在使用编辑按钮,并且想在按下按钮后在控制台上显示特定元素的ID,但不是显示ID,而是显示空白。

I have tried putting other element but none works

/category.tsx

import React, { Component } from 'react'
import {NavLink} from 'react-router-dom'
import { ReactComponent } from '*.svg';
import {showitems} from './userfunctions'
const mystyles = {
    color:'white',
    display:'inline-block'
  } as React.CSSProperties;

interface catprops{}

/ mainclass

export class category extends Component<catprops,any> {
    constructor(props:catprops){
        super(props);
        this.state={
            tableData: [],
            sno:0,
            id:''
        }
        this.handleclick= this.handleclick.bind(this); //for binding the button with particular id
    }
    componentDidMount(){
        showitems().then(res=>{
            if(res==null)
            {
                console.log("not found");
            }
            else
            this.setState({tableData:res});
        })

    }

///用于处理onclick事件的主句柄

    handleclick =(e:any) =>{
        this.setState({[this.state.id]: e.target.value});
        console.log(this.state.id);
    }

/渲染功能

    render() {
        return (
            <div>
                <table className="table">
                    <thead className="thead-dark">
                    <tr>
                    <th>S.no</th>
                    <th>Category Name</th>
                    <th>Description</th>
                    <th>Created On</th>
                    <th>Action</th>

//数据渲染表

                    </tr> </thead>
                    {
                        this.state.tableData.map((res:any,index:any) =>
                    <tr>
                        <td>{index+1}</td>
                        <td>{res.cname}</td>
                        <td>{res.description}</td>
                        <td>{res.created_on}</td>
                        <td><button value={res._id} onClick={this.handleclick}>Edit</button> //this button 
<button>Delete</button></td>
                    </tr>
                    )
                    }
                </table>
            </div>
        )
    }
}

export default category

//期望

I am expecting the Id on the console but it is showing blank on console because I have initialized it as blank.

我希望控制台上有该ID,但由于我已将其初始化为空白,因此它在控制台上显示为空白。

1 个答案:

答案 0 :(得分:0)

这应该有效

    handleclick = (e:any) =>{
        this.setState({id: e.target.value}, () => {
           console.log(this.state.id);
        });
    }