带有响应选择作为弹出式自定义单元格编辑器的农业网格中的键盘事件问题

时间:2019-05-30 07:52:32

标签: reactjs ag-grid react-select ag-grid-react

  

PS:我已经为此悬赏。如果您不明白我在说什么或需要TL,请在DR上张贴   评论,我很乐意

我想使用react-select作为ag-grid的自定义单元格编辑器

这是我的package.json

{
  "name": "Test",
  "version": "1.0.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "3.9.2",
    "@material-ui/icons": "3.0.2",
    "ag-grid-community": "20.1.0",
    "ag-grid-enterprise": "20.1.0",
    "ag-grid-react": "20.1.0",
    "react": "16.8.1",
    "react-dom": "16.8.1",
    "react-select": "^2.4.1",
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "deploy": "npm run build",
    "lint:check": "eslint . --ext=js,jsx;  exit 0",
    "lint:fix": "eslint . --ext=js,jsx --fix;  exit 0",
    "install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && npm install && npm start",
  },
  "optionalDependencies": {
  },
  "devDependencies": {
    "eslint-config-prettier": "4.0.0",
    "eslint-plugin-prettier": "3.0.1"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

index.js

import React from "react";
import ReactDOM from "react-dom";
import Grid from './app/AgGrid'

const colDefs = [
    {
        headerName              : "Test",
        field                   : "test",       
        editor                  : "manyToOne",
        editable                : true,
        suppressKeyboardEvent   : function suppressEnter(params) {
            let KEY_ENTER = 13;
            let KEY_LEFT = 37;
            let KEY_UP = 38;
            let KEY_RIGHT = 39;
            let KEY_DOWN = 40;
            var event = params.event;
            var key = event.which;
            var editingKeys = [KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, KEY_ENTER];
            var suppress = params.editing && editingKeys.indexOf(key) >= 0;
            console.log("suppress "+suppress);
            return suppress;
        },
        cellEditor              : "reactSelectCellEditor",
    },
]

ReactDOM.render(
<Grid
    readOnly={false}
    field={null}
    columnDefs={colDefs}
    editable={true}
    editingMode={null}
    rowData={[]}
/>
,
document.getElementById("root")
);

AgGrid.js

import React, { Component } from 'react'
import { AgGridReact } from 'ag-grid-react'
import 'ag-grid-community/dist/styles/ag-grid.css'
import ReactSelectCellEditor from './ReactSelectCellEditor'

class Grid extends Component {

    constructor(props) {
        super(props);
        this.state = {
            columnDefs  : props.columnDefs,
            rowData     : [],
            isFormOpen  : false,
            editedData  : {
                data        : [],
                rowIndex    : null,
                columns     : []
            },
            frameworkComponents:{
                'reactSelectCellEditor': ReactSelectCellEditor,
            },
        }
    }

    updateRowData = (newData,index) => {
        var unsavedData = this.state.rowData.map((row,i)=>{
            if (i === index) {
                return newData
            }
            else{
                return row
            }
        })
        this.setState({rowData:unsavedData})
    }

    onGridReady = params => {       
    }

    createData = () => {
        let fields = this.state.columnDefs.map(column=>{
            return column.field
        })
        let newData = {}
        fields.map(field=>{
            if (field !== "id") {
                newData[field] = ""
            }           
        })
        newData["delete"] = false
        this.setState({rowData:[...this.state.rowData,newData]})
    }

    toggleModal = () => {
        this.setState({isFormOpen:!this.state.isFormOpen})
    }

    setEditedData = (data) => {
        console.log("editedData",data)
        this.setState({editedData:data})
    }


    render() {
        var defaultColDef = {
            editable:this.state.editable,
            sortable:false
        }

        var initColDefs = this.state.columnDefs.map(colDef=>{
            return {
                ...colDef,
                cellEditorParams:{
                    ...colDef.cellEditorParams,
                }
            }
        })

        var renderedColumnDefs = []
        if (this.props.editingMode === "inline") {
            renderedColumnDefs = [
                ...initColDefs
            ]
        }
        else if (this.props.readOnly) {
            renderedColumnDefs = [...initColDefs]
        }
        else{
            defaultColDef = {
                editable:false,
                sortable:false
            }
            renderedColumnDefs = [
                ...initColDefs,
            ]
        }
        var renderedRowData = []
        this.state.rowData.map(row=>{
            if (row.delete !== true) {
                renderedRowData.push(row)
            }
        })
        return (
            <React.Fragment>
                <AgGridReact
                    defaultColDef                   = {defaultColDef}
                    columnDefs                      = {renderedColumnDefs}
                    rowData                         = {renderedRowData}
                    onGridReady                     = {this.onGridReady}
                    onCellValueChanged              = {this.handleChange}
                    frameworkComponents             = {this.state.frameworkComponents}
                    singleClickEdit                 = {true}
                    stopEditingWhenGridLosesFocus   = {true}
                    reactNext={true}
                />
                <div className="addButton" style={{padding:'5px', border: '1px solid black'}} onClick={()=>this.createData()}>Add</div>
            </React.Fragment>
        );
    } 
}

export default Grid

和ReactSelectCellEditor.js

import React, { Component } from 'react'
import CreatableSelect  from "react-select/lib/Creatable"
import { components } from 'react-select'
import ReactDOM from 'react-dom'

const colourOptions = [
    { value: 'red', label: 'Red' },
    { value: 'blue', label: 'Blue' },
    { value: 'yellow', label: 'Yellow' }
]

class ReactSelectCellEditor extends Component {

    constructor(props) {
        super(props);
        this.state = {
            value : null
        }
        this.handleChange = this.handleChange.bind(this)
    }

    componentDidMount() {
    }

    handleCreateOption = (inputValue:any) => {
    }

    handleChange(selected){
        this.setState({
            value : selected.value
        })
    }

    afterGuiAttached(param) {
        let self = this;
        this.Ref.addEventListener('keydown', function (event) {
            // let key = event.which || event.keyCode
            // if (key === 37 || key === 38 || key === 39 || key === 40 || key === 13) {
            //     event.stopPropagation();
            //     console.log("onKeyDown "+key);
            // }
        });
        this.SelectRef.focus()
    }

    formatCreate = (inputValue) => {
        return (<p> Add: {inputValue}</p>); 
    };

    isPopup(){
        return true
    }

    getValue() {
        return this.state.value
    }

    render() {
        return (
            <div ref = { ref => { this.Ref = ref }} style={{width: '200px'}}> 
                <CreatableSelect
                    onChange                = {this.handleChange}
                    options                 = {colourOptions}
                    formatCreateLabel       = {this.formatCreate}
                    createOptionPosition    = {"first"}
                    ref                     = { ref => { this.SelectRef = ref }}
                />
            </div>
        );
    }
}

export default ReactSelectCellEditor

如您所见,在ag-grid和弹出(不在单元格中)之间进行的简单裸骨组合实现反应选择。

它工作正常,除了默认的ag-grid导航键事件妨碍了反应选择无误地工作。

现在我已经在ag-grid documentation of keyboard navigation while editing

中阅读了有关此问题的解决方案

这是东西:

  1. 首先,我尝试了解决方案1,该方案1是停止自定义单元格编辑器的事件传播。它可以正常工作,但奇怪的是,尽管我在容器中停止了事件冒泡,但没有停止反应冒泡,您可以从中注释掉的脚本中看到,而不是react-select本身。 ReactSelectCellEditor.js,以某种方式,React Select Key Event也停止执行。我不知道为什么当我停止在父元素中传播事件时,作为div子元素的react select事件停止执行。难道不是应该把事件从孩子带到父母吗?所以第一个解决方案是不行。

  2. 对于第二种解决方案,一个奇怪的是ag-grid本身。如文档所述,ag-grid通过定义列定义中的preventKeyboardEvent函数,允许我们拦截键事件。如果编辑模式是 not 弹出窗口,则可以使用。但就我而言,我使用弹出模式,在弹出模式下,我发现在编辑时未触发preventKeyboardEvent,甚至根本没有调用它。

现在我陷入僵局。在第一种解决方案中,react-select行为异常,而在第二种解决方案中,ag-grid行为异常。我该如何解决?

1 个答案:

答案 0 :(得分:1)

让我警告您,此解决方案是一种破解和反模式。如您所言,react select使用SyntheticKeyboardEvent,它一直等到本机事件遍历整个DOM树的循环。但是您可以通过修改代码来调用react select功能,这将允许您从其他组件访问react select组件的方法,这就是为什么这是一种反模式解决方案。

  1. 从colDef中删除suppressKeyboardEvent

  2. 从node_modules / react-select / src / Creatable.js

  3. 复制CreatableSelect组件
  4. 将这些行添加到复制的组件中,以通过onRef进行访问

    componentDidMount() {
       this.props.onRef(this)
    }
    componentWillUnmount() {
       this.props.onRef(undefined)
    }
    
  5. 通过在副本中定义反应选择的控制方法

    focusOption(param) {
       this.select.focusOption(param);
    }
    selectOption(param) {
       this.select.selectOption(param);
    }
    
  6. 然后在渲染组件时添加onRef = { ref => { this.SelectRef = ref }}

  7. 现在,您可以在停止传播之前调用它们来模拟控件

    this.SelectRef.focusOption('up');
    this.SelectRef.focusOption('down');
    
  8. 您可以通过编写这样的方法来访问对选择状态做出反应的权限

    focusedOption() {
       return this.select.state.focusedOption;
    }
    
  9. 通过参考node_modules / react-select / src / Select.js第1142行来完成其余的仿真