简体   繁体   English

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

[英]Handle cell click state on React.js

I have this state defined: 我已定义此状态:

constructor(props){
        super(props);

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

With the following function which contains a fetch, I recieve an array of objects with responseData: 通过以下包含提取的函数,我可以使用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");
            });
    }

This function is called in componentDidMount : 该函数在componentDidMount调用:

componentDidMount(){
        this.getPosts()
    }

The JSON object obtained from the fetch and kept within this.state.products looks like this: 从获取中获取并保存在this.state.products的JSON对象如下所示:

JSON对象的捕获

As shown previously in the fetch, with this line this.setState({posts:responseData}); 如之前的提取中所示,使用以下代码行this.setState({posts:responseData}); I can pass posts to the table where I want title , date and hour to be displayed: 我可以将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)}
                />

The table called is: 调用的表是:

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

With all of this I am able to print the data that I want on the table, looking like this: 使用所有这些,我可以在表上打印所需的数据,如下所示: 在此处输入图片说明

What I am not able to do is: When I click on a row of the table to pass the values that were previously printed, such as the title. 我无法做的是: 当我单击表格的一行以传递先前打印的值(例如标题)时。

在此处输入图片说明

This dialog is constructed using the following lines: 使用以下行构造此对话框:

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

I thought that binding this to handleOpenModify (the function that is called when you click on a row of the table): 我认为,结合thishandleOpenModify (当你点击桌子上的一排被称为功能):

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

Would allow me to print the title within the TextField as simple as giving to the defaultValue this.state.posts.title , but is not working as you can see on the last picture that I added. 允许我在TextField打印标题,就像将defaultValue this.state.posts.title一样简单,但是无法正常工作,就像您在添加的最后一张图片上看到的那样。

PD: I call getPosts() in handleOpenModify in case it had to be called again when a row is clicked, but it hasn't worked either. PD:我在handleOpenModify中调用getPosts()handleOpenModify在单击某行时必须再次调用它,但是它也没有用。

Any suggestions? 有什么建议么?

DataTables provides you the rowNumber and columnIndex as arguments. DataTables为您提供rowNumbercolumnIndex作为参数。

For more information, check their docs: https://github.com/hyojin/material-ui-datatables/blob/master/src/DataTables/DataTablesRow.js#L142 有关更多信息,请查看其文档: 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]) }
/>

this is a sample on how to bind and retrieve specific data on click of cell 这是有关如何单击单元格来绑定和检索特定数据的示例

list item creation 清单项目创建

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

onClick handler onClick处理程序

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

as for your current code, you need to modify this part 至于您当前的代码,您需要修改此部分

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
}

Thanks to @EdwardChopuryan and @Semi-Friends I've been able to retrieve the data that I wanted. 感谢@EdwardChopuryan和@ Semi-Friends,我得以检索到我想要的数据。

First of all I had to change the name of my function handleOpenModify to handleCellClick , since I could pass through the row parameter all I wanted and keep it within post {} , declared before in the sate. 首先,我必须将我的函数handleOpenModify的名称更改为handleCellClick ,因为我可以通过所有需要的row参数,并将其保留在之前在状态中声明的post {}中。

handleCellClick = (y,x,row) => {
        this.getPosts();
        this.setState({
            openModify: true,
            newForm:false,
            post:{...row, _id:row._id,title:row.title}})
    };

Then, on DataTable , bind it on the onCellClick parameter: 然后,在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)}
                />

And call the value that I wanted on the TextField through the defaultValue : 然后通过defaultValueTextField上调用我想要的值:

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

And this is the result! 这就是结果!

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM