Open xccjk opened 2 years ago
const App = () => {
const value = `例子:\n今天天气不错`;
const value1 = `例子:\r今天天气不错`;
return (
<>
<TextArea
placeholder="例子: 今天天气不错"
style={{ height: 80 }}
/>
<br />
<TextArea placeholder={value} style={{ height: 80 }} />
<br />
<TextArea placeholder={value1} style={{ height: 80 }} />
</>
);
};
setDataSource(dataSource.cloneWithRows(JSON.parse(JSON.stringify(data))))
<Table
...
scroll={{ x: 'max-content' }}
/>
最近在使用antd switch时,遇到一个意外的问题,switch组件初始化赋值没成功
import React, { useEffect } from 'react';
import { Form, Switch } from 'antd';
const ModalCreater = ({ data, close, callback }) => {
const [form] = Form.useForm();
const onFinish = async (values) => {};
useEffect(() => {
if (data) {
form.setFieldsValue({
status: !!data.status,
});
} else {
form.setFieldsValue({
status: true,
});
}
}, [data]);
return (
<Form
form={form}
onFinish={onFinish}
>
<Form.Item
label="状态"
name="status"
>
<Switch />
</Form.Item>
...
</Form>
);
};
export default ModalCreater;
发现在赋值是,switch并没有按照指定状态选中
查看form文档得知,form在初始化值是,Form.Item
默认初始化的属性值是value
,这也就是组件值通过value填充的组件都没什么问题,比如Input、Select等,而Switch组件填充值为checked
知道问题原因后就好修改了:设置Form.Item
渲染属性值checked
,通过valuePropName
api来实现
使用方式如下:
<Form.Item
label="状态"
name="status"
valuePropName="checked"
>
<Switch />
</Form.Item>
大功告成!!!
okButtonProps
属性来提交表单设置htmlType
与form
,form
为表单的name
属性
import React from 'react';
import { Form, Modal } from 'antd';
const App = (props) => {
const onFinish = (values) => {
console.log('values', values);
};
return (
<Modal
title='标题'
open={props.visible}
onCancel={() => {}}
destroyOnClose
okButtonProps={{
htmlType: 'submit',
form: 'form',
}}
>
<Form
name='form'
preserve={false}
onFinish={onFinish}
>
...
</Form>
</Modal>
);
};
export default App;
import React, { useRef } from 'react';
import { Form, Modal } from 'antd';
const App = (props) => {
const formRef = useRef();
const onFinish = () => {
const values = formRef.current?.getFieldsValue();
console.log('values', values);
};
return (
<Modal
title='安全验证'
open={props.visible}
onCancel={() => { }}
onOk={onFinish}
destroyOnClose
width={400}
>
<Form
name='form'
preserve={false}
ref={formRef}
>
...
</Form>
</Modal>
);
};
export default App;
在使用过程中,优先使用第一种方式,因为这样可以效验form的rules,通过ref方法只能获取到表单提交的数据,做不到数据的效验
设置失去焦点效验
<Form.Item
name='code'
rules={[
{
required: true,
message: '请输入验证码!',
},
{
pattern: /^\d{4}$/,
message: '请输入4位数字验证码',
},
]}
validateTrigger={['onBlur']}
>
...
</Form.Item>
antd安装启动后报错
Variable @primary-color-hover is undefined
报错前package.json中依赖版本信息:
错误原因:
@ant-design/pro-layout
、@ant-design/pro-table
包版本导致的,锁定为固定版本就可以了"dependencies": { ... "@ant-design/pro-form": "^1.15.1", "@ant-design/pro-layout": "6.15.0", "@ant-design/pro-table": "2.27.1", "antd": "4.9.4", },