首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对React-Data-Grid中的某些列执行验证

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

Stack Overflow用户
提问于 2019-09-25 11:37:09
回答 1查看 1.4K关注 0票数 1

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

所以我在这里有以下代码

代码语言:javascript
复制
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状态为true,当发生这种情况时,我希望description列验证单元格,如果value为空,则返回error background单元格,否则返回default background单元格(简单检查value是否为空)。

当我按下按钮时,似乎无法使validateMode控制台日志工作。它只在页面初始化时显示,或者当单元格发生变化时(比如向单元格插入值时),.I不能在这里进行验证,除非我做错了。

请在这方面帮帮我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-29 23:16:56

真不敢相信我在回答我自己的问题

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

使其正常工作的代码片段

代码语言:javascript
复制
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}
  />
);
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58090828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档