对 React-Data-Grid 中的某些列进行验证

Fre*_*d A 2 reactjs react-data-grid

我想在react-data-grid表上实现验证,其中只有我在列本身中定义的单元格才会被验证,并且只有在状态设置为true时才会发生验证。

所以我这里有以下代码

const [ validateMode, setValidateMode ] = useState(false);
const errorBackground = { backgroundColor: 'some error color in here' }


const DescriptionFormatter = props => {
    const { value, row } = props;
    let template;

    if (!validateMode){
        template = value;
    }

    if (validateMode){
        let validationStyling = Boolean(value.length) ? {} : errorBackground;
        template = <div style={{ ...validationStyling }}>value</div>
    }

    return template;
}

const tableCols = [
    {
        key: 'id',
        name: 'No'
    },
    {
        key: 'name',
        name: 'Name',
        editable: !disabled,
        editor: <AutoComplete options={nameList} />
    },
    {
        key: 'description',
        name: 'Description',
        editable: !disabled,
        formatter: DescriptionFormatter
    }
];
Run Code Online (Sandbox Code Playgroud)

当按下按钮时,它将触发 validateMode 状态为 true,当发生这种情况时,我希望描述列验证单元格,如果值为空则返回错误背景单元格,否则如果其中有值则返回默认背景(简单检查是否值是否为空)。

当我按下按钮时,我似乎无法让 validateMode 控制台日志正常工作。它仅显示在页面初始化上,或者当单元格更改时(例如向其中插入值时)。我无法在此处进行验证,除非我做错了。

请帮我解决这个问题。

Fre*_*d A 5

不敢相信我回答了我自己的问题哈哈

无论如何我已经找到答案了。无法在列定义处进行验证。它必须在数据网格的单元格级别上完成。您可以将状态传递给单元格并在其中进行验证,并通过使用条件 className 来更改单元格的 CSS 以显示验证是 true 还是 false。

使其工作的代码片段

import ReactDataGrid, { Row, Cell } from "react-data-grid";

/* 
  Validator is a state passed from the parent page that indicates whether page is on validation or not, in case
  if dev want the table to validate when a trigger hits the page (like submit button?)
*/
const { validator } = props;

const CustomCell = props => {
  let valueValidation = false;

  if (validator){
    /* Insert custom validation in here */
    return ( <Cell {...props} className={ validator && valueValidation ? '' : classes.error } /> );
  }

  /* If not in validation mode, display normal rows */
  if (!validator){
    return ( <Cell {...props} /> );
  }
}

const CustomRow = props => {
  return ( <Row {...props} cellRenderer={cellProps => <CustomCell {...cellProps} />} /> );
}

return (
  <ReactDataGrid
    rowRenderer={CustomRow}
  />
);
Run Code Online (Sandbox Code Playgroud)

  • 感谢您回答自己的问题 - 这可能看起来很奇怪,但有时这些是最有用的:) (2认同)