我有一个需要根据API中的架构呈现的复选框表:
架构如下:
{
"type": "item1",
"name": "item1",
"read": true,
"write": true
}
我有一个复选框组件,其中包含逻辑。见下文:
import PropTypes from 'prop-types';
import React from 'react';
import { siblingFieldName } from './utils';
const PermissionsCheckbox = ({
field: { name, value, onBlur },
form: { setFieldValue },
disable = false
}) => (
<div>
<input
name={name}
type="checkbox"
value={value}
checked={value}
onChange={() => {
if (name.includes('.write') && value === true) {
setFieldValue(siblingFieldName(name, 'write'), false);
}
if (name.includes('.read') && value === false) {
setFieldValue(siblingFieldName(name, 'read'), true);
}
setFieldValue(name, !value);
}}
onBlur={onBlur}
disable={disable}
/>
</div>
);
PermissionsCheckbox.propTypes = {
field: PropTypes.object,
form: PropTypes.object,
disable: PropTypes.bool
};
export default PermissionsCheckbox;
在渲染表的主要组件中,我有以下逻辑。这会根据属性显示表格及其相应的复选框:
renderField = (field, index) => {
const { keyField } = this.props;
const { type, name, viewable, writable } = field;
return (
<div className="row" key={type}>
<div className="col-4 my-1">{name}</div>
{viewable && (
<div className="col-2 my-1 text-center">
<Field component={PermissionsCheckbox} name={`${keyField}.${index}.read`} />
</div>
)}
{writable && (
<div className="col-2 my-1 text-center">
<Field component={PermissionsCheckbox} name={`${keyField}.${index}.write`} />
</div>
)}
</div>
);
};
我希望从API获取值write: false
的最后一个复选框出现并被禁用。
服务器的响应如下:
{
"type": "item5",
"name": "item5",
"read": true,
"write": false
}
当前逻辑上说如果write: false
,请不要禁用写复选框。我希望它显示出来但被禁用。我正在使用Formik作为表格。
我尝试执行以下操作:
renderField = (field, index) => {
const { keyField } = this.props;
const { type, name, readable, writable, disabled } = field;
return (
<div className="row" key={type}>
<div className="col-4 my-1">{name}</div>
{readable && (
<div className="col-2 my-1 text-center">
<Field component={PermissionsCheckbox} name={`${keyField}.${index}.read`} />
</div>
)}
{writable ? (
<div className="col-2 my-1 text-center">
<Field component={PermissionsCheckbox} name={`${keyField}.${index}.write`} />
</div>
) : (
<div className="col-2 my-1 text-center">
<Field
component={PermissionsCheckbox}
name={`${keyField}.${index}.write`}
disabled={!disabled}
/>
</div>
)}
</div>
);
};
但是它不起作用。它根据已禁用的值显示所有可单击或已禁用的复选框。我在这里做错了什么?还是我的逻辑错了?