React中如何获取tr的id并将其应用到POST API的请求体中
实现动态传递行ID到POST请求的方案
步骤1:新增存储当前选中行ID的状态
你需要在当前组件新增一个状态变量,用来存储点击行对应的ID:
- 函数组件写法:
import { useState } from 'react' // 其他原有声明 const [currentIpoId, setCurrentIpoId] = useState(null)
- 类组件写法:
// 在constructor的state初始化中新增字段 this.state = { // 原有其他state字段 currentIpoId: null }
步骤2:修改按钮点击事件,传递ID到弹窗打开方法
直接在按钮点击时把当前行的data.id作为参数传给弹窗打开函数,不需要依赖按钮DOM的id属性:
<Button variant="outlined" color="primary" onClick={() => handleDialogOpenTwo(data.id)} > Faq </Button>
对应修改handleDialogOpenTwo的实现,接收ID并存入状态:
- 函数组件:
const handleDialogOpenTwo = (id) => { setCurrentIpoId(id) setIsOpenTwo(true) // 原有打开弹窗的逻辑保留 }
- 类组件:
handleDialogOpenTwo = (id) => { this.setState({ currentIpoId: id, isOpenTwo: true }) }
步骤3:将ID传递给弹窗内的表单组件
因为提交逻辑在<FaqPage />组件内,所以需要把存储的当前ID通过props传给该组件:
<Dialog open={isOpenTwo} onClose={handleDialogCloseTwo} className="quistion_Popup"> <DialogContent> <DialogContentText>Add Faq</DialogContentText> {/* 新增props传递ID */} <FaqPage currentIpoId={currentIpoId} /> </DialogContent> </Dialog>
步骤4:替换POST请求中的静态ID
在FaqPage组件的提交逻辑中,把ipoId的静态值替换为props传入的currentIpoId即可:
axios.post('https://test3.com/api/faqs', { ipoId: this.props.currentIpoId, // 类组件写法,函数组件直接用props.currentIpoId faqList:[ { question: this.state.question, answer: this.state.answer, } ] } )
可选优化:关闭弹窗时清空缓存ID
避免下次打开弹窗时复用上次的ID,在关闭弹窗的方法中清空存储的ID:
- 函数组件:
const handleDialogCloseTwo = () => { setCurrentIpoId(null) setIsOpenTwo(false) // 原有关闭逻辑保留 }
- 类组件:
handleDialogCloseTwo = () => { this.setState({ currentIpoId: null, isOpenTwo: false }) }
内容的提问来源于stack exchange,提问作者govind jha
相关产品推荐
相关产品推荐

