javascript - 如何在反应中从动态表中获取行数据
问题描述
我的应用程序中有一个动态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 ...
)
}
推荐阅读
- django - 如何在 django 模板中使用 if else 语句中断循环
- php - 从 laravel 模型中的函数中选择具有值的数据
- angular - Native 和 ShadowDom ViewEncapsulation 有什么区别?
- wso2 - WSO2 完成一个事务后向另一个端点发送消息
- android - 使用 cmake 集成 FFMPEG:链接库时未定义的引用
- docker - docker ls:无法打开目录“。”:权限被拒绝
- json - 使用 jq 从 JSON 中删除重复值
- c - 使用映射共享内存获取“越界”和“变量未初始化”警告
- angular - 角度形式:将错误传递给一组中的形式
- cloud-foundry - UAA 令牌验证中的访问被拒绝