ReactJS 如何将表格首列设置为可点击链接
解决方案
你当前的代码通过Object.values(item).map批量生成表格单元格,这种方式无法单独控制第一列的渲染逻辑。要把第一列设置为链接,需要手动逐个渲染表格列,而不是批量遍历字段值,具体修改如下:
const EditController = () => { const initState = [ {name: "", ipaddr: "", port: 0, sshuser: "", sshport: 0, license: ""}, ]; const [state, setState] = useState(initState); const user = localStorage.getItem("user"); const token = localStorage.getItem("jwt"); const fetchControllers = async () => { try { const res = await axios.post('/exec/editcontroller', {user} , {headers: { 'Content-Type': 'application/json', 'Authorization': token, }}); if(res.status === 200) { setState(res.data); }else { return 'failure'; } }catch(err) { return 'error'; } } useEffect ( () => { console.log('Inside useEffect'); fetchControllers(); }, []); return ( <div className="medium-text"> <div className="center"> <h2>Controllers</h2> <table id="tbl"> <thead> <tr> <th>Name</th> <th>IP Address</th> <th>Port</th> <th>SSH User</th> <th>SSH Port</th> <th>License</th> </tr> </thead> {state.map((item) => ( <tr key={item.id}> {/* 第一列改为链接,href可根据实际需求修改 */} <td> <a href={`/controller/${item.id}`}>{item.name}</a> </td> {/* 手动渲染其他列 */} <td>{item.ipaddr}</td> <td>{item.port}</td> <td>{item.sshuser}</td> <td>{item.sshport}</td> <td>{item.license}</td> </tr> ))} </table> </div> </div> ); } export default EditController;
关键改动说明
- 移除了
Object.values(item).map的批量渲染逻辑,改为手动渲染每一列,实现对第一列的单独控制。 - 第一列用
<a>标签包裹item.name,设置href属性为业务所需的跳转地址(示例用/controller/${item.id},可根据实际场景修改为详情页、编辑页路径)。 - 修正了原代码中不规范的组件导出方式,将
export default {EditController};改为标准的export default EditController;。
内容的提问来源于stack exchange,提问作者Kamal Palei
相关产品推荐
相关产品推荐

