如何在React Hooks的单击按钮上显示组件?

时间:2020-05-11 04:51:07

标签: axios react-hooks

我使用AXOIS从API提取了一个员工数据,并将其显示在HTML表中,并向其添加了一个按钮,该按钮在另一个组件中显示了额外的信息,问题是当我单击该按钮时,它将在所有行中呈现该组件如果表中有两个雇员,并且我想在表中显示有关第一个雇员的更多信息,则该组件将出现在两行中 提取数据的组件:

          componentDidMount(){
        axios.get(('http://localhost:5000/api/findEmployee'),
         { headers: {
         "Content-type": "application/json"
          }}).
        then(response =>{ 
          this.setState({employeeData:response.data }) ;
                    console.log(response.data);
                  }

         )

     .catch(function (error) {
            console.log(error);
          })
            }



           <Table  employeeData={this.state.employeeData}/>

TAble组件

     import React,{useState} from 'react';
    import  EmployeeCard from '../postEmployeeCard';
    const Table = ({employeeData}) => {
    const [showComponent , setShowComponet]=useState(false);

    function onButtonClick(value){
    setShowComponet(true);
    ;



 setVal1(value1);

    } 
    return (
      <table>
       <head>
        <tr>
         <th></th>  
      <th>FirstName </th>  
      <th>LAstName</th>
      <th>Registration Number</th>
      <th>Phone Number</th>


    </tr>
  </thead>
  <tbody>
  { (employeeData.length > 0) ? employeeData.map( (employee , index) => {
       return (
        <tr key={index}>


             <td><button  value= {employee}  onClick={() =>onButtonClick(employee)}> Show </button>
            {showComponent ? <EmployeeCard props={employee}[enter image description here][1]/> : null}
            </td>

          <td>{employee.PhoneNumber }</td>
          <td>{employee.LastName }</td>
          <td>{employee.FirstName }</td>
          <td>{employee.RegistrationNumber}</td>


         </tr>

      )
     }) : <tr><td colSpan="5">Loading...</td></tr> }
  </tbody>
</table>
        );
       }
       export default Table

1 个答案:

答案 0 :(得分:0)

对所有行都使用一个变量。为了解决您的问题,您可以编写一个单独的组件:

const TRow = ({
  index,
  employee
}) => {
  const [showComponent, setShowComponet]=useState(false);
  const onButtonClick = () =>
    setShowComponet(true);

  return <tr key={index}>
    <td><button  value= {employee}  onClick={() =>onButtonClick(employee)}> Show </button>
      {showComponent ? <EmployeeCard props={employee}[enter image description here][1]/> : null}
     </td>
     <td>{employee.PhoneNumber }</td>
     <td>{employee.LastName }</td>
     <td>{employee.FirstName }</td>
     <td>{employee.RegistrationNumber}</td>
   </tr>
}

.......

{ (employeeData.length > 0) ? employeeData.map((employee, i) =>
   <Trow employee={ employee } index={ i } />)
   : <tr><td colSpan="5">Loading...</td></tr> }