antd#Button TypeScript Examples

The following examples show how to use antd#Button. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.tsx    From posthog-foss with MIT License 7 votes vote down vote up
export function editingToast(
    item: string,
    setItemMode:
        | ((mode: DashboardMode | null, source: DashboardEventSource) => void)
        | ((mode: ItemMode | null, source: DashboardEventSource) => void)
): any {
    return toast(
        <>
            <h1>{item} edit mode</h1>
            <p>Tap below when finished.</p>
            <div className="text-right">
                <Button>Finish editing</Button>
            </div>
        </>,
        {
            type: 'info',
            autoClose: false,
            onClick: () => setItemMode(null, DashboardEventSource.Toast),
            closeButton: false,
            className: 'drag-items-toast accent-border',
        }
    )
}
Example #2
Source File: index.tsx    From react_admin with MIT License 6 votes vote down vote up
NotFound: React.FC<{}> = () => {
  return (
    <div className="page-error">
      <div className="flex-error">
        <div className="title">404</div>
        <div className="info">这个页面不存在</div>
        <Button size="large">
          <Link to="/home">返回首页</Link>
        </Button>
      </div>
      <img src={require("src/assets/img/error.gif")} alt="error" />
    </div>
  );
}
Example #3
Source File: temp_trade_20220108.tsx    From shippo with MIT License 6 votes vote down vote up
Page_temp_trade_20220108 = () => {
  const [text, setText] = useState('')
  const [list, setList] = useState<string[]>([])

  const qqList = useMemo(() => text.split(','), [text])

  const find = useCallback(async () => {
    const hr = await services.temp.temp_trade_20220108__find_no_exist({
      list: qqList,
    })
    console.log(qqList)
    console.log(hr.data)
    setList(hr.data.resource)
  }, [qqList])

  return (
    <div>
      <h1>查询没有完成订单的用户</h1>
      <TextArea rows={4} value={text} onChange={(event) => setText(event.target.value)} />
      <Button type="primary" onClick={find}>
        查询
      </Button>
      <Button
        onClick={() => {
          setText('')
          setList([])
        }}
      >
        清除
      </Button>
      <List
        style={{ backgroundColor: '#fff' }}
        bordered
        dataSource={list}
        renderItem={(item) => <List.Item>{item}</List.Item>}
      />
    </div>
  )
}
Example #4
Source File: form-table.tsx    From generator-earth with MIT License 6 votes vote down vote up
getSearchItems() {
        const { getFieldDecorator } = this.props.form;

        return (
            <React.Fragment>
                <Form.Item label={('查询名')}>
                    {getFieldDecorator('name', { initialValue: '' })(
                        // TODO 暂时没发现下面这个Input在编辑器内会抛错,编译正常
                        // @ts-ignore
                        <Input style={{ width: 400 }} placeholder="请输入名称进行查询(胡歌有重复的,不支持模糊查询)"/>
                    )}
                </Form.Item>
                <Form.Item label={('查询ID')} style={{ display: 'none' }}>
                    {getFieldDecorator('type', { initialValue: 'test' })(
                        // 此表单只作为mock数据做筛选搜索作用
                        // @ts-ignore
                        <Input placeholder=""/>
                    )}
                </Form.Item>
                <Form.Item>
                    <Button htmlType="submit">查询</Button>
                </Form.Item>

            </React.Fragment>
        )

    }
Example #5
Source File: ErrorBoundaryTests.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
ButtonRenderTest = (props: ButtonProps & { render: React.ReactNode, text: string }) => {
    const [renderTestComponent, setRenderTestComponent] = useState(false);
    return (
        <>
            <Button {...props} onClick={() => setRenderTestComponent(true)}>{props.text}</Button>
            {renderTestComponent === true && props.render}
        </>
    )
}
Example #6
Source File: sample.tsx    From drip-table with MIT License 6 votes vote down vote up
public render() {
    return (
      <div>
        自定义:
        { ' ' }
        { this.props.data?.status }
        <Button type="link" onClick={() => { this.props.fireEvent({ type: 'custom', name: 'sample-event' }); }}>发起事件</Button>
        { this.props.schema.options.customSchema }
      </div>
    );
  }
Example #7
Source File: Login.tsx    From vite-react-ts with MIT License 6 votes vote down vote up
Login: React.FC = () => {
  const { login, loading } = useStore((state) => ({ ...state }));

  return (
    <div className={cls.loginBox}>
      <Card className="_bg" bordered={false}>
        <Form
          onFinish={({ username, password }) => {
            if (username === 'admin' && password === '123456') {
              return login({ username, password });
            }
            message.error('账号或密码错误,请重试!');
          }}>
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}>
            <Input prefix={<UserOutlined />} placeholder="请输入用户名:admin" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input prefix={<LockOutlined />} placeholder="请输入密码:123456" />
          </Form.Item>
          <Form.Item>
            <Button
              loading={loading}
              type="primary"
              htmlType="submit"
              className={cls.button}>
              登陆
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
Example #8
Source File: SpotifyAuthButton.tsx    From spotify-recently-played-readme with MIT License 6 votes vote down vote up
/**
 * Spotify authentication button.
 */
export default function SpotifyAuthButton(props: Props): JSX.Element {
    // Navigate to authorize URI
    const handleClick = () => {
        window.location.href = getAuthorizeUri(scopes);
    };

    const label = props.label ?? 'Authorize';
    return (
        <Button
            className="spotify-auth-btn"
            onClick={handleClick}
            type="primary"
            shape="round"
            icon={<Icon component={SpotifyIcon} />}
            size="large">
            {label}
        </Button>
    );
}
Example #9
Source File: NavLinkIconButton.tsx    From Shopping-Cart with MIT License 6 votes vote down vote up
NavLinkIconButton: FC<PropTypes> = props => {
  const { to, icon, text } = props;

  return (
    <NavLink to={to}>
      <Button icon={icon}>
        <Text strong={true}>{text}</Text>
      </Button>
    </NavLink>
  );
}
Example #10
Source File: ErrorNetwork.tsx    From posthog-foss with MIT License 6 votes vote down vote up
export function ErrorNetwork(): JSX.Element {
    return (
        <div>
            <h1 className="page-title">Network Error</h1>
            <p>There was an issue loading the requested resource.</p>
            <p>
                <Button onClick={() => window.location.reload()}>
                    <ReloadOutlined /> Reload the page!
                </Button>
            </p>
        </div>
    )
}
Example #11
Source File: edit-policy-access-drawe.tsx    From shippo with MIT License 5 votes vote down vote up
Component: React.ForwardRefRenderFunction<
  EditPolicyAccessDrawerRef,
  EditPolicyAccessDrawerProps
> = (props, ref) => {
  const { onClose } = props
  const [policy, setPolicy] = useState<IPermissionPolicy>(__defaultPolicy)
  const [dataSource, setDataSource] = useState<IPermissionAccess[]>([])

  const [visible, setVisible] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([])

  // ref
  useImperativeHandle(ref, () => {
    return {
      // 打开抽屉
      open: (policy: IPermissionPolicy) => {
        services.permissionAccess.find_all_ext_status({ id: policy.id }).then((hr) => {
          setDataSource(hr.data.resource)
          setSelectedRowKeys(hr.data.resource.filter((item) => item.status).map((item) => item.id))
        })
        setPolicy(policy)
        setVisible(true)
      },
    }
  })

  // 关闭抽屉
  const closeDrawer = useCallback(() => {
    onClose && onClose()
    setVisible(false)
  }, [onClose])

  const handleSave = useCallback(async () => {
    console.log(policy)
    services.permissionPolicy.update_access({ id: policy.id, access: selectedRowKeys })
    closeDrawer()
  }, [policy, selectedRowKeys, closeDrawer])

  return (
    <Drawer
      title="访问规则配置"
      width={720}
      onClose={closeDrawer}
      visible={visible}
      bodyStyle={{ paddingBottom: 80 }}
    >
      <Form layout="vertical" requiredMark={false}>
        <Form.Item>
          <Table
            rowKey="id"
            rowSelection={{
              selectedRowKeys,
              onChange: (keys) => setSelectedRowKeys(keys as number[]),
            }}
            columns={columns}
            dataSource={dataSource}
            size="small"
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button onClick={closeDrawer}>关闭</Button>
            <Button onClick={handleSave} type="primary">
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Drawer>
  )
}
Example #12
Source File: form.tsx    From generator-earth with MIT License 5 votes vote down vote up
render() {
        return (
            <Form className="ui-background" layout="inline" onFinish={this.onFinish}>
                <Form.Item name='assetCode' label={('编号')}>
                    <Input />
                </Form.Item>

                <Form.Item name='assetName' label={('名称')}>
                    <Input />
                </Form.Item>

                <Form.Item name='contract' label={('主体')}>
                    <Select style={{ width: 180 }}>
                        <Select.Option value="lucky">lucky</Select.Option>
                        <Select.Option value="dog">dog</Select.Option>
                    </Select>
                </Form.Item>

                <Form.Item name='signDate' label={('时间')}>
                    <DatePicker.RangePicker format='YYYY年MM月DD HH:mm:ss' />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit"> 查询 </Button>
                </Form.Item>
            </Form>
        )
    }
Example #13
Source File: AppHeader.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
AppHeader = observer(({ children }: { children?: React.ReactNode }) => {
  const intl = useIntl();
  const mainStore = useMainStore();

  const [settingsEnabled, setSettingsEnabled] = useState(false);

  const [visibleHotkeyInfo, setVisibleHotkeyInfo] = useState(false);

  const toggleHotkeyInfo = useCallback<KeyHandler>(
    () => setVisibleHotkeyInfo(!visibleHotkeyInfo),
    [visibleHotkeyInfo]
  );
  useHotkey(toggleHotkeyInfoHotkeyConfig, toggleHotkeyInfo);

  const toggleSettings = useCallback(() => {
    setSettingsEnabled(isEnabled => {
      return !isEnabled;
    });
  }, []);

  const showLogoutConfirm = useCallback(() => {
    modals.open({
      content: intl.formatMessage({ id: "header.logout.areYouSure" }),
      okText: intl.formatMessage({ id: "header.logout.ok" }),
      cancelText: intl.formatMessage({ id: "header.logout.cancel" }),
      onOk: () => mainStore.logout()
    });
  }, [mainStore, intl]);

  return (
    <div className={styles.header}>
      <JmixLightIcon className={styles.icon} />

      <div className={styles.content}>{children}</div>
      <>
        {settingsEnabled && (
          <>
            <ThemeSwitcher className={styles.themeSwitcher} />
            <LanguageSwitcher className={styles.languageSwitcher} />
          </>
        )}
      </>
      <Space className={styles.userPanel}>
        <span>{mainStore.userName}</span>
        <Button
          className={classNames(
            settingsEnabled ? styles.settingsBtnActive : styles.settingsBtn,
            appStyles.focusOuterHighlight
          )}
          type={"text"}
          icon={<SettingOutlined role={""} />}
          onClick={toggleSettings}
          role={"switch"}
          aria-checked={settingsEnabled}
        />
        <HotkeyInfoModalButton
          visible={visibleHotkeyInfo}
          setVisible={setVisibleHotkeyInfo}
          className={classNames(styles.infoBtn, appStyles.focusOuterHighlight)}
        />
        <Button
          id="button_logout"
          className={classNames(
            styles.logoutBtn,
            appStyles.focusOuterHighlight
          )}
          type="text"
          icon={<LogoutOutlined role={""} />}
          onClick={showLogoutConfirm}
        />
      </Space>
    </div>
  );
})
Example #14
Source File: ref.tsx    From drip-table with MIT License 5 votes vote down vote up
Demo = () => {
  const [allSelected, setAllSelected] = useState(false);
  const dripTable: React.MutableRefObject<DripTableInstance | null> = useRef(null);

  function selectAllRecord() {
    const tableInstance = dripTable.current;
    const allKeys = simpleData.map((rec, idx) => idx);
    if (tableInstance) {
      const selectedKeys = tableInstance.selectedRowKeys;
      if (selectedKeys.length < allKeys.length) {
        tableInstance.select(allKeys);
        setAllSelected(true);
      } else {
        tableInstance.select([]);
        setAllSelected(false);
      }
    }
  }

  return (
    <React.Fragment>
      <div style={{ padding: '0 30px 30px', textAlign: 'left' }}>
        <Button style={{ marginRight: '5px' }} type="primary" onClick={selectAllRecord}>
          { allSelected && '取消' }
          全选
        </Button>
      </div>
      <DripTable<SampleRecordType>
        ref={dripTable}
        driver={DripTableDriverAntDesign}
        schema={schema}
        slots={{
          default: props => <div data-slot-type={props.slotType} />,
        }}
        total={simpleData.length}
        dataSource={simpleData}
        onEvent={(event, record, index) => {
          if (event.type === 'drip-link-click') {
            const name = event.payload;
            message.info(`你点击了第${index + 1}行“${record.name} (ID: ${record.id})”的"${name}"事件按钮。`);
            console.log(name, record, index);
          } else if (event.type) {
            message.info(`自定义事件“${event.type}”触发于行“${record.name} (ID: ${record.id})”的自定义组件。`);
            console.log(event, record, index);
          }
        }}
        onSelectionChange={(selectedKeys, selectedRows) => {
          setAllSelected(selectedRows.length >= simpleData.length);
        }}
      />
    </React.Fragment>
  );
}
Example #15
Source File: index.tsx    From spotify-recently-played-readme with MIT License 5 votes vote down vote up
export default function Home(): JSX.Element {
    const router = useRouter();
    const [currentUser, setCurrentUser] = useState<string | undefined>(undefined);
    const error = router.query['error'];

    useEffect(() => {
        // Read 'spotifyuser' cookie
        const user = Cookie.get('spotifyuser');
        if (user) {
            setCurrentUser(user);
        }
    });

    const handleClearCreds = () => {
        Cookie.remove('spotifyuser');
        window.location.reload();
    };

    return (
        <div className="container">
            <Head>
                <title>Spotify Recently Played README Generator</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>

            <Breadcrumb separator=">" style={{ marginBottom: 25 }}>
                <Breadcrumb.Item href="/">Home</Breadcrumb.Item>
            </Breadcrumb>

            <div>
                <Title level={2}>Spotify Recently Played README Generator</Title>
                {error && <Alert message="Error" description={error} type="error" style={{ marginBottom: 18 }} />}

                {!currentUser ? (
                    <Space className="vert-space" direction="vertical" size="middle">
                        <Text>Get started by authorizing the app below.</Text>
                        <SpotifyAuthButton clientId={ClientId} redirectUri={RedirectUri} />
                    </Space>
                ) : (
                    <Space className="vert-space" direction="vertical" size="middle">
                        <MarkdownSnippet username={currentUser} />
                        <SpotifyAuthButton clientId={ClientId} redirectUri={RedirectUri} label="Re-authorize" />
                        <Button type="link" danger onClick={handleClearCreds}>
                            Clear local credentials
                        </Button>
                    </Space>
                )}
            </div>
        </div>
    );
}
Example #16
Source File: AppEditorLink.tsx    From posthog-foss with MIT License 5 votes vote down vote up
export function AppEditorLink({
    actionId,
    style,
    children,
}: {
    actionId?: number
    style?: React.CSSProperties
    children: React.ReactNode
}): JSX.Element {
    const [modalOpen, setModalOpen] = useState(false)
    const { currentTeam } = useValues(teamLogic)

    return (
        <>
            <Button
                href={appEditorUrl(currentTeam?.app_urls?.[0], actionId)}
                style={style}
                size="small"
                onClick={(e) => {
                    e.preventDefault()
                    setModalOpen(true)
                }}
            >
                {children}
            </Button>
            <Modal
                visible={modalOpen}
                title={
                    actionId
                        ? 'Choose the domain on which to edit this action'
                        : 'Choose the domain on which to create this action'
                }
                footer={<Button onClick={() => setModalOpen(false)}>Close</Button>}
                onCancel={() => setModalOpen(false)}
            >
                <AuthorizedUrlsTable actionId={actionId} pageKey="app-editor-link" />
            </Modal>
        </>
    )
}
Example #17
Source File: index.tsx    From react_admin with MIT License 4 votes vote down vote up
FromAdd: React.FC<{}> = props => {
  const [visible, setVisible] = useState(false)
  const [form] = Form.useForm()

  const submitData = (values: any) => {
    setVisible(false)
    message.success('提交数据成功!!!')
    form.resetFields()
  }
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  }
  return (
    <>
      <Button
        onClick={() => setVisible(true)}
        size="large"
        type="primary"
        className="btn-bottom"
      >
        添加新数据
      </Button>
      <Modal
        title="提交数据"
        onCancel={() => setVisible(false)}
        visible={visible}
        footer={null}
      >
        <Form
          form={form}
          initialValues={{ ji: true, level: 2020 }}
          name="basic"
          onFinish={submitData}
          onFinishFailed={onFinishFailed}
          {...layout}
        >
          <Form.Item label="时间" name="time" rules={[{ required: true }]}>
            <DatePicker format="YYYY-MM-DD" />
          </Form.Item>
          <Form.Item label="赛事名称" name="title" rules={[{ required: true }]}>
            <Input placeholder="请输入赛事名称" />
          </Form.Item>
          <Form.Item label="赛事级别" name="ji" rules={[{ required: true }]}>
            <Radio.Group>
              <Radio value={true}>省赛</Radio>
              <Radio value={false}>校赛</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="年度" name="level" rules={[{ required: true }]}>
            <InputNumber max={2020} min={2010} />
          </Form.Item>
          <Form.Item label="学校" name="school" rules={[{ required: true }]}>
            <Input placeholder="请输入学校" />
          </Form.Item>
          <Form.Item label="地址" name="address" rules={[{ required: true }]}>
            <Input placeholder="请输入地址" />
          </Form.Item>
          <Form.Item label="描述信息" name="desc" rules={[{ required: true }]}>
            <Input placeholder="请输入描述信息" />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button
                onClick={() => form.resetFields()}
                type="default"
                htmlType="reset"
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
Example #18
Source File: index.tsx    From covid_dashboard with MIT License 4 votes vote down vote up
render() {
    const regionInfo = this.props.regionInfo || {name_en: '', name_zh: ''}
    let fullName = this.props.env.lang === 'en' ? regionInfo.name_en : regionInfo.name_zh
    if (fullName === 'United States of America') fullName = "United States"
    else if (fullName === 'People\'s Republic of China') fullName = "China"
    fullName = fullName.replace('Republic', 'Rep.').replace('Democratic', 'Dem.')
    const ep = this.props.dayEp
    let active: number | undefined = ep ? ((ep.confirmed||0) - (ep.cured||0) - (ep.dead||0)) : undefined;
    let active_delta: number | undefined = ep ? ((ep.confirmed_delta||0) - (ep.cured_delta||0) - (ep.dead_delta||0)) : undefined;
    return (
      <div className='dashboard'>
        <div className='up'>
          <div className='left'>
            <DBBlock style={{width: `${this.props.env.isMobile ? this._leftWidth_m : this._leftWidth}px`, height: `${this._upHeight}px`}}>
              <div className='region'>{fullName}</div>
              <Tooltip 
                title={this.props.env.lang == 'zh' ? "风险指数" : "Risk Index"}
                placement='bottom'>
                <div className='risk'>
                  <div className='value' style={{color: risk2color(ep?.risk)}}>{displayNumber(ep?.risk)}</div>
                  <div className='title'>Risk Index</div>
                  <span className='tip' onClick={() => window.open("https://covid-dashboard.aminer.cn/algorithm/?lang="+this.props.env.lang)}><Tip_Svg /></span>
                </div>
              </Tooltip>
              <div className='mode-con'>
                <MapModeSelector mapMode={this.props.mapMode} onSetMapMode={this.props.onSetMapMode}/>
              </div>
            </DBBlock>
            <DBBlock style={{width: `${this.props.env.isMobile ? this._leftWidth_m : this._leftWidth}px`, height: `${this._timeHeight}px`}}>
              <div className='time'>{dateformat(this.props.env.date, "yyyy/mm/dd HH:MM:ss")}</div>
            </DBBlock>
          </div>
          { 
            !this.props.env.isMobile && (
              <div className='right'>
                <div className='rightup'>
                  <DBBlock style={{width: `${this._dataWidth}px`, height: `${this._rightupHeight}px`}}>
                    <Tooltip title={this.props.env.lang == 'zh' ? "累计确诊" : "Total Confirmed"} placement='top' >
                      <div>
                        <div className='data-delta' style={{color: 'lightsalmon'}}><i className="fas fa-plus"/><span className="agg">{displayNumber(ep?.confirmed_delta)}</span></div>
                        <div className='data' style={{color: 'red'}}><i className="fas fa-medkit"/><span className="agg">{displayNumber(ep?.confirmed)}</span></div>
                      </div>
                    </Tooltip>
                  </DBBlock>
                  <DBBlock style={{width: `${this._dataWidth}px`, height: `${this._rightupHeight}px`}}>
                    <Tooltip title={this.props.env.lang == 'zh' ? "现存确诊" : "Active"} placement='top' >
                      <div>
                        <div className='data-delta' style={{color: 'lightgoldenrodyellow'}}><i className="fas fa-plus"/><span className="agg">{displayNumber(active_delta)}</span></div>
                        <div className='data' style={{color: 'khaki'}}><i className="fas fa-diagnoses"/><span className="agg">{displayNumber(active)}</span></div>
                      </div>
                    </Tooltip>
                  </DBBlock>
                  <DBBlock style={{width: `${this._dataWidth}px`, height: `${this._rightupHeight}px`}}>
                    <Tooltip title={this.props.env.lang == 'zh' ? "治愈" : "Cured"} placement='top' >
                      <div>
                        <div className='data-delta' style={{color: 'palegreen'}}><i className="fas fa-plus"/><span className="agg">{displayNumber(ep?.cured_delta)}</span></div>
                        <div className='data' style={{color: 'lime'}}><i className="fas fa-star-of-life"/><span className="agg">{displayNumber(ep?.cured)}</span></div>
                      </div>
                    </Tooltip>
                  </DBBlock>
                  <DBBlock style={{width: `${this._dataWidth}px`, height: `${this._rightupHeight}px`}}>
                    <Tooltip title={this.props.env.lang == 'zh' ? "死亡" : "Dead"} placement='top' >
                      <div>
                        <div className='data-delta' style={{color: 'gainsboro'}}><i className="fas fa-plus"/><span className="agg">{displayNumber(ep?.dead_delta)}</span></div>
                        <div className='data' style={{color: 'darkgrey'}}><i className="fas fa-skull-crossbones"/><span className="agg">{displayNumber(ep?.dead)}</span></div>
                      </div>
                    </Tooltip>
                  </DBBlock>
                </div>
                <div className='rightdown'>
                  <DBBlock style={{width: `${this._riskWidth}px`, height: `${this._rightdownHeight}px`}}>
                    <div className='chart-con'>
                      <ReactEcharts option={this.riskOption()} style={{height: `${this._rightdownHeight-12}px`, width: '100%'}}/>
                      <div className='title'><FormattedMessage id='map.control.riskchart' /></div>
                    </div>
                  </DBBlock>
                  <div className='hot-btns' style={{width: `${this._dataWidth}px`, height: `${this._rightupHeight}`}}>
                    <Button className='hot-btn' onClick={() => this.props.onChangeHotRegion && this.props.onChangeHotRegion("beijing")}><FormattedMessage id="hot.beijing" /></Button>
                  </div>
                </div>
                <div className='rightsearch'>
                  <SearchBar lang={this.props.env.lang} width={this._riskWidth} height={this._rightupHeight} onSearch={this.handleSearch} onClose={this.handleSearchClose} />
                </div>
              </div>
            )
          }
        </div>
        { 
          this.state.searchResults && (
            <div className='searchresults'>
              <SearchResults 
                lang={this.props.env.lang} 
                date={this.props.env.date}
                data={this.state.searchResults} 
                defaultWidth={this._leftWidth+this._riskWidth+this._blockMargin} 
                maxHeight={document.body.offsetHeight-this._blockMargin*2-this._upHeight-220}
                onOpenEntity={this.props.onOpenEntity}
                onOpenEvent={this.props.onOpenEvent} />
            </div>
          )
        }
      </div>
    )
  }
Example #19
Source File: index.tsx    From shippo with MIT License 4 votes vote down vote up
Page_passport = () => {
  const history = useNavigate()

  const handleSmsSend = (phone: string) => {
    console.log('handleSmsSend', { phone })
    if (!checkPhone(phone)) {
      return message.info('手机号格式错误')
    }
    services.captcha.send({ phone })
    message.success('验证码已经发送')
  }

  const [form] = Form.useForm<{ phone: string; captcha: string }>()

  const onFinish = async (values: { phone: string; captcha: string }) => {
    console.log('Received values of form: ', values)
    const { phone, captcha: code } = values

    if (!checkPhone(phone)) {
      return message.info('手机号格式错误')
    }
    if (!checkSmsCode(code)) {
      return message.info('短信验证码格式错误')
    }
    const { data } = await services.user.login({
      phone,
      code,
    })
    window.localStorage.setItem('__PASSPORT', data.resource.passport)
    history('/')
  }

  return (
    <Layout>
      <Header
        style={{
          background: 'transparent',
          textAlign: 'center',
          height: '200px',
          lineHeight: '200px',
        }}
      >
        <span
          style={{
            color: 'rgba(0,0,0,.85)',
            fontWeight: 600,
            fontSize: '33px',
          }}
        >
          Shippo Admin
        </span>
      </Header>
      <Content>
        <div style={{ width: '328px', margin: '0 auto' }}>
          <Form form={form} name="register" onFinish={onFinish} scrollToFirstError>
            <Form.Item name="phone" rules={[{ required: true, message: '请输入你的手机号!' }]}>
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                placeholder="请输入你的手机号!"
                style={{ width: '100%' }}
                allowClear
                size="large"
              />
            </Form.Item>

            <Form.Item>
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                <Form.Item
                  name="captcha"
                  noStyle
                  rules={[{ required: true, message: '请输入验证码!' }]}
                >
                  <Input
                    prefix={<UserOutlined className="site-form-item-icon" />}
                    placeholder="请输入验证码!"
                    style={{
                      flex: 1,
                      marginRight: 8,
                    }}
                    size="large"
                  />
                </Form.Item>
                <Button
                  style={{
                    display: 'block',
                  }}
                  onClick={() => handleSmsSend(form.getFieldValue('phone'))}
                  size="large"
                >
                  获取验证码
                </Button>
              </div>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" style={{ width: '100%' }} size="large">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </Content>
      <Footer
        style={{
          textAlign: 'center',
          marginBottom: '25px',
          color: 'rgba(0,0,0,.45)',
          fontSize: '14px',
        }}
      >
        <CopyrightOutlined /> 2021 Shippo
      </Footer>
    </Layout>
  )
}