antd#message TypeScript Examples
The following examples show how to use
antd#message.
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: root-router.tsx From shippo with MIT License | 6 votes |
Component: React.FC<RootRouteProps> = ({ result }) => {
const history = useNavigate()
const location = useLocation()
useMount(() => {
console.log(result)
const resource = result[0].data.resource
localStorage.setItem('__PASSPORT', resource.passport)
if (resource.uid > 0) {
message.success(`已经登录,UID为${resource.uid}`)
if (location.pathname.startsWith('/passport')) {
history('/')
}
} else {
message.error('没有登录')
history('/passport')
}
})
return (
<Routes>
<Route path="/passport" element={<Passport />}>
<Route path="" element={<Page_passport />}></Route>
</Route>
<Route path="/dashboard" element={<Home />}>
<Route path="" element={withLoading(lazy(() => import('~/pages/dashboard')))}></Route>
</Route>
<Route path="/read" element={<ReadLayout />}></Route>
<Route path="/creation" element={<CreationLayout />}></Route>
<Route path="*" element={<Navigate to="/dashboard" replace />}></Route>
</Routes>
)
}
Example #2
Source File: store.ts From generator-earth with MIT License | 6 votes |
@action setLoading = () => {
const {commonTableStore} = this.rootStore;
commonTableStore.setLoading(true);
message.success('5秒后loading消失')
setTimeout(() => {
commonTableStore.setLoading(false);
}, 5000)
}
Example #3
Source File: Login.tsx From vite-react-ts with MIT License | 6 votes |
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 #4
Source File: operations.ts From dnde with GNU General Public License v3.0 | 6 votes |
Copy = ({ mjmlJson, setActive, setMjmlJson, setCopyActive, setDelActive, target, uidGenerator }: CopyProps) => {
const uniqueIdentifier = findUniqueIdentifier(target, target.classList);
let parentUniqueIdentifier = '';
let index = -1;
if (uniqueIdentifier) {
const _ = getIndexOfElementInParent(target, mjmlJson, uniqueIdentifier);
if (_ && typeof _[0] === 'number' && typeof _[1] === 'string') {
[index, parentUniqueIdentifier] = _;
} else {
message.error('Unable to copy element');
return;
}
}
let copyOfConfig = findElementInJson(mjmlJson, uniqueIdentifier);
if (copyOfConfig && index > -1) {
[copyOfConfig] = copyOfConfig;
setCopyActive(false);
setDelActive(false);
setActive(null);
return AddAtIndex({
droppedConfig: _.cloneDeep(copyOfConfig),
setMjmlJson,
mjmlJson,
uid: uidGenerator,
index,
parentUniqueClassIdentifier: parentUniqueIdentifier,
});
}
}
Example #5
Source File: all.tsx From useTable with MIT License | 6 votes |
Component = () => {
const selectionPlugin = useSelectionPlugin({ primaryKey: 'phone' });
const sortablePlugin = useSortablePlugin();
const filterPlugin = useFilterPlugin();
const { tableProps, paginationProps, getSelectedRowKeys } = useAntdTable(list, {
plugins: [filterPlugin, selectionPlugin, sortablePlugin],
});
return (
<Fragment>
<p>
<Button
onClick={() => {
const selectedRowKeys = getSelectedRowKeys() || [];
message.success(selectedRowKeys.join(','));
}}
>
点击查看勾选值
</Button>
</p>
<Table scroll={{ y: 300 }} {...tableProps}>
<Table.Column title="email" dataIndex="email" filters={filters} />
<Table.Column title="phone" dataIndex="phone" sorter />
<Table.Column title="gender" dataIndex="gender" />
</Table>
<Pagination style={{ marginTop: 16 }} {...paginationProps} />
</Fragment>
);
}
Example #6
Source File: index.tsx From antdp with MIT License | 6 votes |
checkedCode = (code: number | undefined, msg: string | undefined) => {
if (code === 1) {
message.success(msg)
} else if (code === -1) {
message.error(msg)
} else if (code === 200) {
message.success(msg)
} else if (code === 400) {
message.error(msg)
} else if (code === 500) {
message.error(msg)
} else {
message.warn(msg)
}
}
Example #7
Source File: form.tsx From XFlow with MIT License | 6 votes |
CmdForm = () => {
const { commandService } = usePanelContext()
const [form] = Form.useForm<IFormValues>()
const onFinish = async (values: IFormValues) => {
commandService.executeCommand<NsNodeCmd.BackNode.IArgs>(XFlowNodeCommands.BACK_NODE.id, values)
console.log('executeCommand with args', values)
message.success(`${XFlowNodeCommands.BACK_NODE.label}: 命令执行成功`)
form.setFieldsValue({
nodeId: values.nodeId === 'node1' ? 'node2' : 'node1',
})
}
return (
<FormBuilder<IFormValues>
form={form}
formItems={formItems}
onFinish={onFinish}
initialValues={{
nodeId: 'node1',
}}
/>
)
}
Example #8
Source File: App.tsx From brick-design with MIT License | 6 votes |
export default function App() {
const [isPreview,setIsPreview]=useState(false)
return (
<BrickProvider
config={config}
warn={(msg: string) => {
message.warning(msg)
}}
>
<div className={styles['wrapper']}>
<ToolBar />
<div className={styles['content']}>
<AllComponents />
<div className={styles['canvas-container']}>
<Radio.Group defaultValue={'0'} style={{marginBottom:20}}
onChange={(e)=>setIsPreview(e.target.value==='1')}>
<Radio.Button value={'0'}>
编辑
</Radio.Button>
<Radio.Button value='1'>
预览
</Radio.Button>
</Radio.Group>
{isPreview?<PreviewPanel/>:<DesignPanel />}
</div>
<Resizable
enable={RIGHT_ENABLE}
defaultSize={{ width: '150px', height: '100%' }}
className={styles['props-shadow']}
>
<SettingsPanel />
</Resizable>
</div>
</div>
</BrickProvider>
)
}
Example #9
Source File: http.ts From ql with MIT License | 6 votes |
errorHandler = function (error: any) {
if (error.response) {
const message = error.data
? error.data.message || error.data
: error.response.statusText;
if (error.response.status !== 401 && error.response.status !== 502) {
message.error(message);
} else {
console.log(error.response);
}
} else {
console.log(error.message);
}
throw error; // 如果throw. 错误将继续抛出.
}
Example #10
Source File: ColorGroup.tsx From next-basics with GNU General Public License v3.0 | 6 votes |
export function ColorCube(props: ColorCubeProps) {
const { color } = props;
const handleCopy = (text: string) => {
message.success(`\`${text}\` copied`);
};
return (
<div className={style.cubeContainer}>
<Clipboard text={`var(${color})`} onCopy={handleCopy}>
<span
className={style.cube}
style={{ backgroundColor: `var(${color})` }}
/>
</Clipboard>
</div>
);
}
Example #11
Source File: bindListeners.ts From next-core with GNU General Public License v3.0 | 6 votes |
function builtinMessageListenerFactory(
method: "success" | "error" | "info" | "warn",
args: unknown[],
ifContainer: IfContainer,
context: PluginRuntimeContext
): EventListener {
return function (event: CustomEvent) {
if (!looseCheckIf(ifContainer, { ...context, event })) {
return;
}
const processArg = argsFactory(args, context, event) as Parameters<
typeof message["success"]
>;
const contentNode = React.createElement(
"span",
null,
`${processArg[0]}`
) as React.ReactNode;
const argProp = {
content: contentNode,
className: `ant-message-notice-${method}`,
} as ArgsProps;
processArg[0] = argProp;
message[method](...processArg);
} as EventListener;
}
Example #12
Source File: PageLogin.tsx From yugong with MIT License | 6 votes |
PageLogin:React.FC<Props> = () => {
const { setAuth } = useDispatch<Dispatch>().controller;
const history = useHistory();
const onLogin = useCallback(
(user: userResult) => {
setAuth({
isLogin: true,
session: user
})
history.push('/project');
message.success('登录成功')
},
[history, setAuth],
)
return (
<div className={s.loginwrap}>
<div className={s.main}>
<Login labelCol={5} onLogin={onLogin} />
<div className={s.space} />
</div>
</div>
)
}
Example #13
Source File: index.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
TimeSpanFilterItem = ({
itemData,
value,
active,
onVisibleChange,
onChange,
onQuickOperation,
labels,
}: Merge<IFilterItemProps<'timespanRange'>, { labels: JSX.Element }>) => {
const [duration, setDuration] = React.useState();
useEffectOnce(() => {
setDuration(value);
});
const { key, label, placeholder, disabled } = itemData;
return (
<span className="contractive-filter-item">
{labels}
<Duration
value={duration}
onChange={(v) => {
const durationMin = transformDuration(v?.[0]);
const durationMax = transformDuration(v?.[1]);
if (isNumber(durationMin) && isNumber(durationMax)) {
if (durationMin <= durationMax) {
onChange({ key, value: v });
} else {
message.error(i18n.t('msp:wrong duration'));
}
} else if (!isNumber(durationMin) && !isNumber(durationMax)) {
onChange({ key, value: [] });
}
}}
/>
</span>
);
}
Example #14
Source File: root-router.tsx From shippo with MIT License | 5 votes |
Component: React.FC<RootRouteProps> = ({ result }) => {
const history = useNavigate()
const location = useLocation()
useMount(() => {
console.log(result)
const resource = result[0].data.resource
localStorage.setItem('__PASSPORT', resource.passport)
if (resource.uid > 0) {
message.success(`已经登录,UID为${resource.uid}`)
if (location.pathname.startsWith('/passport')) {
history('/')
}
} else {
message.error('没有登录')
history('/passport')
}
})
return (
<Routes>
<Route path="/passport" element={<Passport />}>
<Route path="" element={<Page_passport />}></Route>
</Route>
<Route path="/transform" element={<Transform />}></Route>
<Route path="/dashboard" element={<Home />}>
<Route path="" element={withLoading(lazy(() => import('~/pages/dashboard')))}></Route>
</Route>
<Route path="/users" element={<Home />}>
<Route path="" element={withLoading(lazy(() => import('~/pages/users')))}></Route>
</Route>
<Route path="/temp/*" element={<Home />}>
<Route
path="temp_trade_20220108"
element={withLoading(lazy(() => import('~/pages/temp/temp_trade_20220108')))}
></Route>
</Route>
<Route path="/permission/*" element={<Home />}>
<Route
path="role"
element={withLoading(lazy(() => import('~/pages/permission/role')))}
></Route>
<Route
path="access"
element={withLoading(lazy(() => import('~/pages/permission/access')))}
></Route>
<Route
path="policy"
element={withLoading(lazy(() => import('~/pages/permission/policy')))}
></Route>
</Route>
<Route path="*" element={<Navigate to="/dashboard" replace />}></Route>
</Routes>
)
}
Example #15
Source File: store.ts From generator-earth with MIT License | 5 votes |
/**
* 获取数据主方法
* @desc 参数详情 请查看RequestParams
*/
@action
async getData({url, type, sourceId, params = {}, headers = {}}: RequestParams): Promise<any> {
const {commonTableStore:store} = this.rootStore;
const info: AllDataSourceParams = store.allDataSource[sourceId];
// 如果没传参数 则吧默认值传进去
params = {
pageSize: info.pageSize,
pageNo: info.pageNo,
...params
}
store.isLoading = true;
const result: ResultParams = await request[type](url, params, headers);
store.setState({isLoading: false});
// 值不存在的时候
if (!result) {
return message.error('请求异常');
}
// 当code 为其他值 请求失败的时候
if (result.code !== 0) {
return message.error(result.msg);
}
store.setDataSource(sourceId, {
...result.data,
...params,
});
// 设置请求相关的url 和 type
if (!store.allRequestInfo[sourceId]) {
store.setSubState('allRequestInfo', sourceId, {url, type});
}
return result;
}
Example #16
Source File: Login.tsx From jmix-frontend with Apache License 2.0 | 5 votes |
Login = observer(() => {
const intl = useIntl();
const mainStore = useMainStore();
const [login, setLogin] = useState("");
const [password, setPassword] = useState("");
const [performingLoginRequest, setPerformingLoginRequest] = useState(false);
const changeLogin = useCallback((e: ChangeEvent<HTMLInputElement>) => setLogin(e.target.value), [setLogin]);
const changePassword = useCallback((e: ChangeEvent<HTMLInputElement>) => setPassword(e.target.value), [setPassword]);
const doLogin = useCallback(() => {
setPerformingLoginRequest(true);
mainStore
.login(login, password)
.then(action(() => {
setPerformingLoginRequest(false);
}))
.catch(action((error: JmixServerError) => {
setPerformingLoginRequest(false);
const loginMessageErrorIntlId = loginMapJmixRestErrorToIntlId(error);
message.error(intl.formatMessage({id: loginMessageErrorIntlId}));
}));
}, [setPerformingLoginRequest, mainStore, intl, login, password]);
return (
<Card className={styles.loginForm}>
<JmixDarkIcon className={styles.logo} />
<div className={styles.title}>
<%= title %>
</div>
<Form layout='vertical' onFinish={doLogin}>
<Form.Item>
<Input id='input_login'
placeholder={intl.formatMessage({id: 'login.placeholder.login'})}
onChange={changeLogin}
value={login}
prefix={<UserOutlined style={{ margin: "0 11px 0 0" }}/>}
size='large'/>
</Form.Item>
<Form.Item>
<Input id='input_password'
placeholder={intl.formatMessage({id: 'login.placeholder.password'})}
onChange={changePassword}
value={password}
type='password'
prefix={<LockOutlined style={{ margin: "0 11px 0 0" }}/>}
size='large'/>
</Form.Item>
<Form.Item>
<div className={styles.languageSwitcherContainer}>
<LanguageSwitcher />
</div>
</Form.Item>
<Form.Item>
<Button type='primary'
htmlType='submit'
size='large'
block={true}
loading={performingLoginRequest}>
<FormattedMessage id='login.loginBtn'/>
</Button>
</Form.Item>
</Form>
</Card>
);
})
Example #17
Source File: ref.tsx From drip-table with MIT License | 5 votes |
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 #18
Source File: index.tsx From ii-admin-base with MIT License | 5 votes |
InputVerify: FC<InputVerifyProps> = props => {
const {
sendCode,
countDown,
initCodeText,
reCodeText,
codeClassname,
checkPhone,
...restProps
} = props;
const [codeText, setCodeText] = useState(initCodeText);
const [codeStatus, setCodeStatus] = useState(false);
// 处理倒计时时间
const handleCountDown = (
timer: ReturnType<typeof setTimeout> | null,
count: number,
) => {
if (timer) {
clearTimeout(timer);
}
if (count <= 0) {
setCodeText(reCodeText);
setCodeStatus(false);
} else {
setCodeText(`${count} s`);
const newTimer: ReturnType<typeof setTimeout> = setTimeout(() => {
handleCountDown(newTimer, count - 1);
}, 1000);
}
};
// 处理验证码点击
const handleCodeClick = () => {
if (codeStatus) return;
// 有校验条件但是不通过
if (checkPhone && !checkPhone()) {
message.error('请输入正确手机号!');
return;
}
sendCode && sendCode();
setCodeStatus(true);
handleCountDown(null, countDown as number);
};
const codeCls = classNames('ii-verify-button', codeClassname, {
'ii-verify-button-disabled': codeStatus,
});
return (
<Input
data-testid="test-input-verify"
{...restProps}
suffix={
<span className={codeCls} onClick={handleCodeClick}>
{codeText}
</span>
}
/>
);
}
Example #19
Source File: Messages.tsx From dnde with GNU General Public License v3.0 | 5 votes |
success = (msg: string) => {
message.success(msg);
}
Example #20
Source File: useSketchJSON.ts From html2sketch with MIT License | 5 votes |
useSketchJSON = () => {
const [sketchJSON, setJSON] = useState<object>();
const parserFactory = async (
elements: Element | Element[],
parserFunc: (
el: Element,
) => Promise<SketchFormat.Group | SketchFormat.SymbolMaster>,
) => {
try {
console.groupCollapsed('[html2sketch]开始转换...');
let result;
if (elements instanceof Array) {
const objects: Object[] = [];
for (let i = 0; i < elements.length; i += 1) {
const el = elements[i];
// eslint-disable-next-line no-await-in-loop
const symbolJSON = await parserFunc(el);
objects.push(symbolJSON);
}
result = objects;
} else {
result = await parserFunc(elements);
}
console.groupEnd();
console.log('解析结果:', result);
copy(JSON.stringify(result));
setJSON(result);
await message.success('转换成功? 已复制到剪切板');
return result;
} catch (e) {
await message.error('解析失败,请检查 Console 输出 ?');
console.groupEnd();
console.groupEnd();
console.error('报错如下:');
console.error(e);
}
};
/**
* 生成 Group 的方法
* @param elements
*/
return {
sketchJSON,
generateSymbol: async (elements: Element | Element[]) => {
await parserFactory(elements, async (el: Element) =>
(await nodeToSketchSymbol(el)).toSketchJSON(),
);
},
generateGroup: async (elements: Element | Element[]) => {
await parserFactory(elements, async (el: Element) =>
(await nodeToGroup(el)).toSketchJSON(),
);
},
};
}
Example #21
Source File: index.tsx From S2 with MIT License | 5 votes |
Export: React.FC<ExportProps> = React.memo((props) => {
const {
className,
icon,
syncCopy = false,
copyOriginalText = i18n('复制原始数据'),
copyFormatText = i18n('复制格式化数据'),
downloadOriginalText = i18n('下载原始数据'),
downloadFormatText = i18n('下载格式化数据'),
successText = i18n('操作成功'),
errorText = i18n('操作失败'),
sheet,
fileName,
...restProps
} = props;
const PRE_CLASS = `${S2_PREFIX_CLS}-export`;
const copyData = (isFormat: boolean) => {
const data = getSheetData(sheet, '\t', isFormat);
copyToClipboard(data, syncCopy)
.then(() => {
message.success(successText);
})
.catch((error) => {
// eslint-disable-next-line no-console
console.log('copy failed: ', error);
message.error(errorText);
});
};
const downloadData = (isFormat: boolean) => {
const data = getSheetData(sheet, ',', isFormat);
try {
download(data, fileName);
message.success(successText);
} catch (err) {
message.error(errorText);
}
};
const menu = (
<Menu>
<Menu.Item key="copyOriginal" onClick={() => copyData(false)}>
{copyOriginalText}
</Menu.Item>
<Menu.Item key="copyFormat" onClick={() => copyData(true)}>
{copyFormatText}
</Menu.Item>
<Menu.Item key="downloadOriginal" onClick={() => downloadData(false)}>
{downloadOriginalText}
</Menu.Item>
<Menu.Item key="downloadFormat" onClick={() => downloadData(true)}>
{downloadFormatText}
</Menu.Item>
</Menu>
);
return (
<Dropdown
overlay={menu}
trigger={['click']}
className={cx(PRE_CLASS, className)}
{...restProps}
>
<a
className="ant-dropdown-link"
key="export"
onClick={(e) => e.preventDefault()}
>
{icon || <DotIcon />}
</a>
</Dropdown>
);
})
Example #22
Source File: form.tsx From XFlow with MIT License | 5 votes |
CmdForm = () => {
const { commandService } = usePanelContext()
const [form] = Form.useForm<IFormValues>()
const [hasGroup, setGroup] = React.useState(false)
const onFinish = async (values: IFormValues) => {
const nodeConfig = {
...values,
groupHeaderHeight: parseInt(values.groupHeaderHeight as any, 10),
groupPadding: parseInt(values.groupPadding as any, 10),
groupCollapsedSize: GROUP_COLLAPSED_SIZE,
}
setGroup(true)
console.log(nodeConfig)
await commandService.executeCommand<NsGroupCmd.AddGroup.IArgs>(
XFlowGroupCommands.ADD_GROUP.id,
{
nodeConfig: nodeConfig,
},
)
message.success(`${XFlowGroupCommands.ADD_GROUP.label}: 命令执行成功`)
}
return (
<FormBuilder<IFormValues>
form={form}
formItems={formItems}
onFinish={onFinish}
initialValues={{
id: uuidv4(),
groupChildren: ['node1', 'node2', 'node3', 'node4'],
label: 'Group_1',
groupHeaderHeight: 40,
groupPadding: 12,
renderKey: GROUP_NODE_RENDER_ID,
}}
submitButton={
<Button type="primary" htmlType="submit" style={{ width: '100%' }} disabled={hasGroup}>
执行命令
</Button>
}
/>
)
}
Example #23
Source File: edit.tsx From yforms with MIT License | 5 votes |
Demo: React.FC<RouteComponentProps> = (props) => {
const { match = {} as RouteComponentProps['match'] } = props;
const [data, setData] = useState({});
const [loading, setLoading] = useState(true);
const [form] = YForm.useForm();
const { formatFieldsValue, onFormatFieldsValue } = YForm.useFormatFieldsValue();
const {
submit,
submit: {
params: { id, typeName },
},
} = YForm.useSubmit({ params: match.params });
useEffect(() => {
setTimeout(() => {
if (id) {
setData({ name: '张三', age: '10' });
}
setLoading(false);
}, 10);
}, [id]);
onFormatFieldsValue([
{ name: 'append_field', format: () => '提交前追加字段' },
{ name: 'name', format: (value) => `${value}_改变了` },
]);
const onFinish = async (values: any) => {
console.log('Success:', values);
await new Promise((resolve) => setTimeout(resolve, 500));
await new Promise((resolve, reject) => {
// 请求随机成功或者失败
if (Math.round(Math.random()) === 0) {
reject();
message.error('提交错误', 0.5);
} else {
resolve('');
message.success('提交成功', 0.5);
}
});
};
const onSave = async (values: any) => {
console.log('values:', values);
await new Promise((resolve) => setTimeout(resolve, 500));
await message.success('保存成功', 0.5);
};
const onFinishFailed = (errorInfo: any) => {
console.log('Failed:', errorInfo);
};
return (
<>
<h2>{typeName}</h2>
<YForm
form={form}
submit={submit}
initialValues={data}
name="basic"
onFinish={onFinish}
onFinishFailed={onFinishFailed}
formatFieldsValue={formatFieldsValue}
loading={loading}
onSave={onSave}
params={match.params}
>
{[
{ type: 'input', label: 'name', name: 'name' },
{ type: 'input', label: 'age', name: 'age', componentProps: { suffix: '岁' } },
{ type: 'money', label: 'money', name: 'money' },
{ type: 'submit' },
]}
</YForm>
</>
);
}
Example #24
Source File: index.tsx From LogicFlow with Apache License 2.0 | 5 votes |
export default function ApproveExample() {
const [lf, setLf] = useState({} as LogicFlow);
const [nodeData, setNodeData] = useState();
useEffect(() => {
const lf = new LogicFlow({
...config,
container: document.querySelector('#graph') as HTMLElement
});
setLf(lf);
RegisteNode(lf);
lf.render(data);
initEvent(lf);
}, []);
const initEvent = (lf: LogicFlow) => {
lf.on('element:click', ({ data }) => {
setNodeData(data);
console.log(JSON.stringify(lf.getGraphData()));
});
lf.on('connection:not-allowed', (data: any) => {
message.error(data.msg);
});
}
// 更新属性
const updateProperty = (id: string, data: any) => {
const node = lf.graphModel.nodesMap[id];
const edge = lf.graphModel.edgesMap[id];
if (node) {
node.model.setProperties(Object.assign(node.model.properties, data));
} else if (edge) {
edge.model.setProperties(Object.assign(edge.model.properties, data));
}
}
// 隐藏属性面板
const hidePropertyPanel = () => {
setNodeData(undefined);
}
return (
<div className="approve-example-container">
<div className="node-panel">
{ NodePanel(lf) }
</div>
<div id="graph" className="viewport" />
{ nodeData ? <div className="property-panel">
{PropertyPanel(nodeData, updateProperty, hidePropertyPanel)}
</div> : ''}
</div>
)
}
Example #25
Source File: index.tsx From ql with MIT License | 5 votes |
Config = () => {
const [width, setWidth] = useState('100%');
const [marginLeft, setMarginLeft] = useState(0);
const [marginTop, setMarginTop] = useState(-72);
const [value, setValue] = useState('');
const [loading, setLoading] = useState(true);
const getConfig = () => {
setLoading(true);
request
.get(`${config.apiPrefix}config/config`)
.then((data: any) => {
setValue(data.data);
})
.finally(() => setLoading(false));
};
const updateConfig = () => {
request
.post(`${config.apiPrefix}save`, {
data: { content: value, name: 'config.sh' },
})
.then((data: any) => {
message.success(data.msg);
});
};
useEffect(() => {
if (document.body.clientWidth < 768) {
setWidth('auto');
setMarginLeft(0);
setMarginTop(0);
} else {
setWidth('100%');
setMarginLeft(0);
setMarginTop(-72);
}
getConfig();
}, []);
return (
<PageContainer
className="ql-container-wrapper"
title="config.sh"
extra={[
<Button key="1" type="primary" onClick={updateConfig}>
保存
</Button>,
]}
header={{
style: {
padding: '4px 16px 4px 15px',
position: 'sticky',
top: 0,
left: 0,
zIndex: 20,
marginTop,
width,
marginLeft,
},
}}
>
<CodeMirror
value={value}
options={{
lineNumbers: true,
styleActiveLine: true,
matchBrackets: true,
mode: 'shell',
}}
onBeforeChange={(editor, data, value) => {
setValue(value);
}}
onChange={(editor, data, value) => {}}
/>
</PageContainer>
);
}
Example #26
Source File: LicenseNotification.tsx From next-basics with GNU General Public License v3.0 | 5 votes |
export function notificationFactory(expires: number) {
const handleClose = () => {
storage.setItem(getUnionKey(EXPIRING_DISMISSED), true);
// 7 天内不在提示
storage.setItem(
getUnionKey(EXPIRING_DISMISSED_UNTIL),
moment().unix() + 7 * 86400
);
notification.close(LICENSE_INFO);
};
const handleDelay = async () => {
const { org } = getAuth();
try {
await CustomerApi_setOrgUpdating({
orgId: org,
});
message.success("已申请延期");
handleClose();
} catch (err) {
handleHttpError(err);
}
};
const renderBtn = () => {
return (
<Button type="link" onClick={handleClose} className={styles.closeBtn}>
{" "}
不再提示{" "}
</Button>
);
};
const renderContent = () => {
return (
<>
<div style={{ marginTop: 15 }}>
你的 org 即将在{" "}
<span className={styles.highlight}>
{moment.unix(expires).format("YYYY-MM-DD")}
</span>{" "}
过期,请联系 EasyOps 续期。{" "}
</div>
<span>或点击</span>
<Button type="link" onClick={handleDelay}>
一键申请延期
</Button>
</>
);
};
return notification.warning({
key: LICENSE_INFO,
message: "提示",
duration: 0,
description: renderContent(),
btn: renderBtn(),
style: {
width: 580,
},
});
}
Example #27
Source File: antd.ts From next-core with GNU General Public License v3.0 | 5 votes |
message.config({ top: 40 });
Example #28
Source File: Login.tsx From yugong with MIT License | 5 votes |
Login: React.FC<Props> = ({ labelCol, wrapperCol, onLogin }) => {
const onFinish = useCallback(
(values: any) => {
loading.show();
login(values)
.then(user => {
loading.hide();
if (onLogin instanceof Function) {
onLogin(user)
}
}).catch(({ error }) => {
loading.hide();
message.error(error || '登录失败')
});
},
[onLogin]
);
const onFinishFailed = (errorInfo: any) => {
console.log("Failed:", errorInfo);
};
return (
<>
<h2 style={{ textAlign: "center", marginBottom: "20px" }}>登录</h2>
<Form
name="basic"
labelCol={{ span: labelCol || 8 }}
wrapperCol={{ span: wrapperCol || 16 }}
initialValues={{ remember: true }}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
label="用户名"
name="username"
rules={[{ required: true, message: "请输入用户名!" }]}
>
<Input />
</Form.Item>
<Form.Item
label="密码"
name="password"
rules={[{ required: true, message: "请输入密码!" }]}
>
<Input.Password />
</Form.Item>
<Form.Item
name="remember"
valuePropName="checked"
wrapperCol={{ offset: labelCol || 8, span: wrapperCol || 16 }}
>
<Checkbox>记住密码</Checkbox>
</Form.Item>
<Form.Item
wrapperCol={{ offset: labelCol || 8, span: wrapperCol || 16 }}
>
<Button type="primary" htmlType="submit">
登录
</Button>
</Form.Item>
</Form>
</>
);
}
Example #29
Source File: App-vite.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
setConfig('onAPISuccess', message.success);