React 使用state, onchange获取数据

React 使用state, onchange获取数据

创建dialog

import React, { useState } from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogActions from '@material-ui/core/DialogActions';
import { TextField, Typography } from '@material-ui/core';

export function ExampleDialog() {
  const [open, setOpen] = useState(false);
  // 初始化formData值
  const [formData, setFormData] = React.useState({
    id: '',
    name: '',
    description: '',
  });
  const handleClickOpen = () => {
    setOpen(true);
  };
  /**
   * 监听onchange
   * @param val 
   * @param type 
   */
  const  handlerSetFormData = (val: string, type: string) => {
    setFormData({ ...formData, [type]: val} )
  }

  const handleClose = () => {
    setOpen(false);
  };

  /**
   * save
   */
  const handleSave = async() => {
    const res = await fetch('http://127.0.0.1:7007/api/tags' + '/insert', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          id: formData.id,
          name: formData.name,
          description: formData.description
        }),
      })
    if (res) {
      setOpen(false);
      window.location.reload();
    }
  };

  return (
    <div>
      <Button variant="contained" color="primary" onClick={handleClickOpen}>
        New Tag
      </Button>
      <Dialog open={open}>
        <DialogTitle>Dialog Title</DialogTitle>
        <DialogContent>
          <DialogContentText>
            To add or update tag,  please enter your tag name, description here. We will send updates
          </DialogContentText>
          <TextField required autoFocus  id='id' name='id' label='Tag Id' type='text' fullWidth disabled={true} value={formData.id} onChange={(e) => handlerSetFormData(e.target.value, 'id')}  />
          <TextField required autoFocus  id='name' name='name' label='Tag Name' type='text' fullWidth value={formData.name} onChange={(e) => handlerSetFormData(e.target.value, 'name')} />
          <TextField autoFocus  id='description' name='description' label='Tag Description' type='text' fullWidth value={formData.description} onChange={(e) => handlerSetFormData(e.target.value, 'description')} />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} color="primary">
            Cancel
          </Button>
          <Button onClick={handleSave} color="primary">
            OK
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}

示例

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值