[英]How to get a row data from a dynamic table in react
我的应用程序中有一个动态table
,我从一个 api 获取它的数据,我需要获取它的参数并添加一些其他参数,然后将其发布到另一个 api。
这是我的code
:
edit = (data) => {
console.log()
}
return (
<div className="App">
<TableContainer component={Paper}>
<Table className={classes.table} aria-label="customized table">
<TableHead>
<TableRow>
<TableCell>Horse Name(ENG)</TableCell>
<TableCell>Owner</TableCell>
<TableCell>Microchip id</TableCell>
<TableCell>Number</TableCell>
<TableCell>Round</TableCell>
</TableRow>
</TableHead>
<TableBody>
{product
.filter((item) => {
if (search == []) {
return item;
}
})
.map((item) => {
return (
<TableRow key={item.id}>
<TableCell component="th" scope="row">
{item.nameEn}
</TableCell>
<TableCell component="th" scope="row">
{item.owner}
</TableCell>
<TableCell component="th" scope="row">
{item.chipNumber}
</TableCell>
<TableCell component="th" scope="row">
<TextField label="number" variant="standard" />
</TableCell>
<TableCell component="th" scope="row">
<TextField label="Round" variant="standard" />
</TableCell>
<TableCell component="th" scope="row">
<Button variant="primary"
value={loading ? 'Loading...' : 'Publish'}
onClick={() => edit(item)}
// onClick={handleAdd}
disabled={loading}>Add to round</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
</div>
);
}
问题是我不知道如何将表中的行数据作为字符串传递给edit
,我想在调用编辑函数时,它会在行上打印参数之一
这对我有一点帮助,但我不知道为什么它不能很好地工作并且它不能将data
识别为function
。 如果它有明显的问题,我真的是一个新手抱歉!
您几乎实现了它,但是您的编辑功能没有正确定义。
function SampleComponent () {
// rest of the codes ...
const addToRoundHandler = (selectedItem) => {
console.log(selectedItem) // ---> print your selected item object!
console.log(`Item name : ${selectedItem.nameEn} and the owner ${selectedItem.owner}`)
// you might need to call an API to send the selected item to the server
}
return (
// rest of the codes ...
<TableCell component="th" scope="row">
<Button
variant="primary"
value={loading ? 'Loading...' : 'Publish'}
onClick={() => addToRoundHandler(item)} // ---> here
disabled={loading}
>
Add to round
</Button>
</TableCell>
// rest of the codes ...
)
}
注意代码的注释。 我用一些有意义的名字来更好地解释,你可以改变它们。
如果要在页面上显示所选项目,则需要创建一个状态变量:
function SampleComponent () {
const [currentItem, setCurrentItem] = useState({})
// rest of the codes ...
const addToRoundHandler = (selectedItem) => {
console.log(selecteItem);
setCurrentItem(currentItem)
}
// rest of the codes ...
return (
// rest of the codes ...
<div>
{
currentItem.length > 0 && <p> You selected: {currentItem.name} </p>
}
</div>
// rest of the codes ...
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.