【问题标题】:Doing validation on certain columns in React-Data-Grid对 React-Data-Grid 中的某些列进行验证
【发布时间】:2019-09-25 03:37:08
【问题描述】:

我想在 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
    }
];

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

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

请帮助我。

【问题讨论】:

    标签: reactjs react-data-grid


    【解决方案1】:

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

    反正我已经找到答案了。无法在列定义处进行验证。它必须在数据网格的单元格级别上完成。您可以将状态传递给单元格并在那里进行验证,并使用条件 className 更改单元格的 CSS 以显示验证是真还是假。

    使其工作的代码片段

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

    【讨论】:

    • 感谢您回答您自己的问题 - 这可能看起来很奇怪,但有时这些是最有用的 :)
    猜你喜欢
    • 2017-04-13
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2021-05-14
    • 2023-04-08
    相关资源
    最近更新 更多