如何在 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}/>

塔布尔组件

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

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

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> }

相关内容

  • 没有找到相关文章

最新更新