index.tsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import React from 'react';
  2. import { Form, Tooltip, Button } from '@douyinfe/semi-ui';
  3. import { IconHelpCircle } from '@douyinfe/semi-icons';
  4. /**
  5. * @description input, button may trigger submit of form
  6. *
  7. * case 1: 当 form 中只有一个 input,在 input 上敲击 enter 会触发 form submit
  8. * case 2: 当 form 中有 2 个 input,在任意一个 input 上敲击 enter 都不会触发 form submit
  9. * case 3: 当 from 中有一个 input 和一个 button,在 input 上敲击 enter 会触发 form submit
  10. *
  11. * @summary 如果不想触发 form submit,监听 input key down,如果 `e.key` 等于 `Enter` 则调用 e.preventDefault
  12. *
  13. * @see https://github.com/DouyinFE/semi-design/issues/767#issuecomment-1098836675
  14. */
  15. const App = () => {
  16. const { Option } = Form.Select;
  17. return (
  18. <Form
  19. onSubmit={() => console.log('submit')}
  20. onSubmitFail={(errors, values) => console.log(errors, values)}
  21. >
  22. <Form.Select field="Role" label='角色' style={{ width: 176 }}>
  23. <Option value="admin">管理员</Option>
  24. <Option value="user">普通用户</Option>
  25. <Option value="guest">访客</Option>
  26. </Form.Select>
  27. <Form.Input field='UserName' label='用户名' style={{ width: 80 }} onKeyDown={e => {
  28. if (e.key === 'Enter') {
  29. e.preventDefault();
  30. }
  31. }} />
  32. <Form.Input
  33. field='Password'
  34. label={{
  35. text: '密码',
  36. extra: <Tooltip content='详情'><IconHelpCircle style={{ color: '--semi-color-text-1' }} /></Tooltip>
  37. }}
  38. rules={[{ message: '密码长度至少为6位', validator: (_, value) => value?.length >= 6 }]}
  39. style={{ width: 176 }}
  40. />
  41. <Button htmlType="submit">提交</Button>
  42. </Form>
  43. );
  44. };
  45. App.storyName = 'form submit';
  46. export default App;