我想在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状态为true,当发生这种情况时,我希望description列验证单元格,如果value为空,则返回error background单元格,否则返回default background单元格(简单检查value是否为空)。
当我按下按钮时,似乎无法使validateMode控制台日志工作。它只在页面初始化时显示,或者当单元格发生变化时(比如向单元格插入值时),.I不能在这里进行验证,除非我做错了。
请在这方面帮帮我。
发布于 2019-09-29 23:16:56
真不敢相信我在回答我自己的问题
不管怎样,我已经找到答案了。无法在列定义中执行验证。它必须在数据网格的单元级别上完成。您可以将状态传递给单元格并在那里进行验证,并通过使用条件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}
/>
);https://stackoverflow.com/questions/58090828
复制相似问题