簡體   English   中英

處理React.js上的單元格點擊狀態

[英]Handle cell click state on React.js

我已定義此狀態:

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()
    }

從獲取中獲取並保存在this.state.products的JSON對象如下所示:

JSON對象的捕獲

如之前的提取中所示,使用以下代碼行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");
        }
    }
];

使用所有這些,我可以在表上打印所需的數據,如下所示: 在此處輸入圖片說明

我無法做的是: 當我單擊表格的一行以傳遞先前打印的值(例如標題)時。

在此處輸入圖片說明

使用以下行構造此對話框:

                 <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>

我認為,結合thishandleOpenModify (當你點擊桌子上的一排被稱為功能):

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

允許我在TextField打印標題,就像將defaultValue this.state.posts.title一樣簡單,但是無法正常工作,就像您在添加的最后一張圖片上看到的那樣。

PD:我在handleOpenModify中調用getPosts()handleOpenModify在單擊某行時必須再次調用它,但是它也沒有用。

有什么建議么?

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]) }
/>

這是有關如何單擊單元格來綁定和檢索特定數據的示例

清單項目創建

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
}

感謝@EdwardChopuryan和@ Semi-Friends,我得以檢索到我想要的數據。

首先,我必須將我的函數handleOpenModify的名稱更改為handleCellClick ,因為我可以通過所有需要的row參數,並將其保留在之前在狀態中聲明的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)}
                />

然后通過defaultValueTextField上調用我想要的值:

<TextField
      fullWidth={true}
      floatingLabelText="Título"
      errorText="¡Ups! No deberías ver este mensaje."
      defaultValue={this.state.post.title}
           />

這就是結果!

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM