处理React.js上的单元格单击状态

时间:2017-09-04 11:47:54

标签: javascript reactjs

我定义了这个状态:

constructor(props){
        super(props);

        this.state = {
            posts:[],
            post:{},
            openNew:false,
            openModify:false
        };
    }

使用包含fetch的以下函数,我收到一个带有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对象如下所示:

CAPTURE OF THE JSON OBJECT

如前面提到的那样,使用此行this.setState({posts:responseData});,我可以将posts传递到我想要titledatehour的表格中显示:

<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");
        }
    }
];

通过所有这些,我能够在桌面上打印出我想要的数据,如下所示: enter image description here

我无法做的是:当我点击表格的一行以传递之前打印的值时,例如标题。

enter image description here

使用以下行构建此对话框:

                 <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绑定到handleOpenModify(单击表格行时调用的函数):

handleOpenModify = () => {
        this.getPosts();
        this.setState({openModify: true});
    };

允许我在TextField中打印标题就像给予defaultValue this.state.posts.title一样简单,但是在我添加的最后一张图片上看不到。

P.D。:我在getPosts()中调用handleOpenModify,以防在点击某行时再次调用它,但它也没有用。

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

DataTables为您提供rowNumbercolumnIndex作为参数。

有关详情,请查看他们的文档: 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]) }
/>

答案 1 :(得分:0)

这是关于如何在单击单元格上绑定和检索特定数据的示例

列出项目创建

var list = CAMPAIGN_TABLE_COLUMNS.map((data, key) =>
    <td onClick={this.handleClick.bind(this, key)}>{data.title}</td>
)

onClick处理程序

handleClick(id) {
    let item = CAMPAIGN_TABLE_COLUMNS[id]; // item data
}

对于您当前的代码,您需要修改此部分

onCellClick={this.handleOpenModify.bind(this)} // key or the array index

handleOpenModify(e, row, key) { // receive the column number as 3rd param
  let item = CAMPAIGN_TABLE_COLUMNS[key]; // now get the respective object
}

答案 2 :(得分:0)

感谢@EdwardChopuryan和@ Semi-Friends,我已经能够检索到我想要的数据。

首先,我必须将我的函数handleOpenModify的名称更改为handleCellClick,因为我可以通过我想要的row参数并将其保留在{{1}内在国家声明之前。

post {}

然后,在handleCellClick = (y,x,row) => { this.getPosts(); this.setState({ openModify: true, newForm:false, post:{...row, _id:row._id,title:row.title}}) }; 上,将其绑定到DataTable参数:

onCellClick

通过<DataTables height={'auto'} selectable={false} showRowHover={true} columns={CAMPAIGN_TABLE_COLUMNS} data={this.state.posts} showCheckboxes={false} rowSizeLabel="Filas por página" onCellClick={this.handleCellClick.bind(this)} />

TextField上调用我想要的值
defaultValue

这就是结果!

enter image description here

相关问题