我们在开发前端页面的时候,为了方便开发会引用流行的 UI 组件库,其中 Antd UI 组件库是其中的佼佼者。尤其是 Form 组件功能强大,提供的 api 丰富。
如果我们想设置 Form 中的 Label 和 内容的显示宽度,就需要用到 labelCol
和 wrapperCol
控制布局。但是官方的 demo 和指导都是在建议使用 Grid 栅格类的布局方式。如下
import { Form, Input, Button, Checkbox } from 'antd'; const Demo = () => { const onFinish = (values: any) => { console.log('Success:', values); }; const onFinishFailed = (errorInfo: any) => { console.log('Failed:', errorInfo); }; return ( <Form name="basic" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} initialValues={{ remember: true }} onFinish={onFinish} onFinishFailed={onFinishFailed} autoComplete="off" > <Form.Item label="Username" name="username" rules={[{ required: true, message: 'Please input your username!' }]} > <Input /> </Form.Item> <Form.Item label="Password" name="password" rules={[{ required: true, message: 'Please input your password!' }]} > <Input.Password /> </Form.Item> <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 8, span: 16 }}> <Checkbox>Remember me</Checkbox> </Form.Item> <Form.Item wrapperCol={{ offset: 8, span: 16 }}> <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> </Form> ); }; ReactDOM.render(<Demo />, mountNode);
这种方式,需要对不同的宽度尺寸进行设置,不是很方便。在我们都比较确定 Label 的的长度的情况下,其实可以设置 labelCol 和 wrapperCol 的 style 像素宽度做到,像 Button 之类的可以设置 margin-left。 如下
import { Form, Input, Button, Checkbox } from 'antd'; const Demo = () => { const onFinish = (values) => { console.log('Success:', values); }; const onFinishFailed = (errorInfo) => { console.log('Failed:', errorInfo); }; return ( <Form name="basic" labelCol={{ style: { width: 120 } }} wrapperCol={{ style: { width: 'calc(100% - 120px)' } }} initialValues={{ remember: true, }} onFinish={onFinish} onFinishFailed={onFinishFailed} autoComplete="off" > <Form.Item label="Username" name="username" rules={[ { required: true, message: 'Please input your username!', }, ]} > <Input /> </Form.Item> <Form.Item label="Password" name="password" rules={[ { required: true, message: 'Please input your password!', }, ]} > <Input.Password /> </Form.Item> <Form.Item name="remember" valuePropName="checked" wrapperCol={{ style: { marginLeft: 120, width: 'calc(100% - 120px)', } }} > <Checkbox>Remember me</Checkbox> </Form.Item> <Form.Item wrapperCol={{ style: { marginLeft: 120, width: 'calc(100% - 120px)', } }} > <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> </Form> ); }; ReactDOM.render(<Demo />, document.getElementById('container'));
看,这样是不是左边的 label 我们就设置好了呢。