我定义了这个状态:
constructor(props){
super(props);
this.state = {
posts:[],
post:{},
openNew:false,
openModify:false
};
}
通过以下包含提取的函数,我收到一个带有responseData的对象数组:
getPosts(){
fetch(
DOMAIN+'/api/posts/', {
method: 'get',
dataType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer '+this.props.token
}
})
.then((response) =>
{
return response.json();
})
.then((responseData) => {
this.setState({posts:responseData});
console.log("Log del responseData de posts");
console.log(responseData);
})
.catch(function() {
console.log("error");
});
}
该函数在componentDidMount
中调用:
componentDidMount(){
this.getPosts()
}
从 fetch 中获取并保存在 this.state.products
中的 JSON 对象如下所示:
如前面的获取所示,通过此行 this.setState({posts:responseData});
我可以将 posts
传递到我想要的表要显示的标题
、日期
和小时
:
<DataTables
height={'auto'}
selectable={false}
showRowHover={true}
columns={CAMPAIGN_TABLE_COLUMNS}
data={this.state.posts}
showCheckboxes={false}
rowSizeLabel="Filas por página"
onCellClick={this.handleOpenModify.bind(this)}
/>
调用的表是:
const CAMPAIGN_TABLE_COLUMNS = [
{
key: 'title',
label: 'Título',
style:{width: '40%'}
}, {
key: 'created',
label: 'Fecha',
style:{width: '30%'},
render: (DateToFormat) => {
return moment(DateToFormat).format("DD/MM/YYYY");
}
}, {
key: 'created',
label: 'Hora',
style:{width: '30%'},
render: (DateToFormat) => {
return moment(DateToFormat).format("hh:mm:ss");
}
}
];
我无法做的是:当我单击表格的一行来传递之前打印的值(例如标题)时。
此对话框是使用以下几行构建的:
<Dialog
title="Modificar Post"
actions={actions}
modal={false}
open={this.state.openModify}
onRequestClose={this.handleClose}
titleClassName="dialog-title"
contentStyle={{width:660}}
autoScrollBodyContent={true}
>
<TextField
fullWidth={true}
floatingLabelText="Título"
errorText="¡Ups! No deberías ver este mensaje."
defaultValue={this.state.posts.title}
/>
</Dialog>
我认为将 this
绑定(bind)到 handleOpenModify
(单击表格的一行时调用的函数):
handleOpenModify = () => {
this.getPosts();
this.setState({openModify: true});
};
允许我在 TextField
中打印标题,就像赋予 defaultValue
this.state.posts.title
一样简单,但是正如您在我添加的最后一张图片中看到的那样,它不起作用。
P.D.:我在 handleOpenModify
中调用 getPosts()
,以防在单击一行时必须再次调用它,但它也不起作用。
有什么建议吗?
最佳答案
DataTables
为您提供 rowNumber
和 columnIndex
作为参数。
有关更多信息,请查看他们的文档: https://github.com/hyojin/material-ui-datatables/blob/master/src/DataTables/DataTablesRow.js#L142
<DataTables
...
onCellClick={(event, rowNumber) => console.log('selectedPost', this.state.posts[rowNumber]) }
/>
关于javascript - 处理 React.js 上的单元格单击状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46036384/