React Hooks MUI ,父子传值,双向绑定,memo,useCallback

React Hooks MUI ,父子传值,双向绑定,memo,useCallback 用法。

  • useCallback 配合 memo使用避免重复渲染子组件。
  • 子组件封装成表单,方便直接调用。

子组件

import { useState, memo } from "react";
import {
  Grid,
  FormControl,
  FormLabel,
  FormControlLabel,
  Checkbox,
  FormGroup,
  TextField,
  InputLabel,
  Select,
  MenuItem,
  RadioGroup,
  Radio,
} from "@mui/material";

const ComponentsForm = memo((props: any) => {
  console.log("子组件更新...");
  // props
  const { setFormData, parentFormData, isDisable } = props;

  // 通用逻辑
  const handleChange = (event: any) => {
    const { name, value, type, checked } = event.target;
    const newValue = type === "checkbox" ? checked : value;
    setFormData((prevValues: any) => ({
      ...prevValues,
      [name]: newValue,
    }));
  };

  const [CheckboxList, setCheckboxList] = useState([
    { id: "0",name: "苹果",value: "1", isCheck: false, },
    { id: "1", name: "香蕉",value: "2",isCheck: false,},
    { id: "2", name: "橘子", value: "3", isCheck: false },
   
  ]);

  // 获取勾选处理

  const list = parentFormData.experimentProject.split(",");
  for (const item of CheckboxList) {
    for (const v of list) {
      if (item.value === v) {
        item.isCheck = true;
      }
    }
  }

  // 单个复选框逻辑;
  const handleCheckChange = (event: any) => {
    let newCheckboxList = [...CheckboxList];
    newCheckboxList[event.target.id].isCheck = event.target.checked;
    setCheckboxList(newCheckboxList);
    // 判断是否选中且返回数组对象
    // eslint-disable-next-line array-callback-return, consistent-return
    const newCheckboxListStr = newCheckboxList.map((v: any) => {
      return v.isCheck === true ? v.value : undefined;
    });
    console.log(newCheckboxListStr);
    // 删除undefined
    const CheckStr = newCheckboxListStr.filter((res: string) => {
      return res !== undefined;
    });
    setFormData((preVal: any) => {
      return {
        ...preVal,
        experimentProject: CheckStr.join(),
      };
    });
  };

  return (
    <Grid container spacing={2}>
      <Grid item xs={12}>
        <FormControl>
          <FormLabel id="demo-row-radio-buttons-group-label">
            实验项目
          </FormLabel>
          <FormGroup row>
            {CheckboxList.map((v) => (
              <FormControlLabel
                key={v.id}
                control={
                  <Checkbox
                    disabled={isDisable}
                    checked={v.isCheck}
                    onChange={handleCheckChange}
                    name={v.name}
                    size="small"
                    id={v.id}
                  />
                }
                label={v.value}
              />
            ))}
          </FormGroup>
        </FormControl>
      </Grid>
      <Grid item xs={4}>
        <FormControl>
          <FormLabel id="demo-row-radio-buttons-group-label">性别</FormLabel>
          <RadioGroup
            row
            aria-labelledby="demo-row-radio-buttons-group-label"
            name="radioValue"
            value={parentFormData.radioValue}
            onChange={handleChange}
          >
            <FormControlLabel value="女" control={<Radio />} label="女" />
            <FormControlLabel value="男" control={<Radio />} label="男" />
          </RadioGroup>
        </FormControl>
      </Grid>

      <Grid item xs={4}>
        <TextField
          disabled={isDisable}
          fullWidth
          required
          id="outlined-required"
          label="数量"
          name="experimentWorkQuantity"
          value={parentFormData.experimentWorkQuantity}
          onChange={handleChange}
        />
      </Grid>
      <Grid item xs={4}>
        <TextField
          disabled={isDisable}
          fullWidth
          id="outlined-basic"
          label="开始时间"
          variant="outlined"
          name="planStartDate"
          value={parentFormData["planStartDate"]}
          onChange={handleChange}
        />
      </Grid>
      <Grid item xs={4}>
        <FormControl fullWidth>
          <InputLabel id="demo-simple-select-label">需求是否合理</InputLabel>
          <Select
            name="needReasonableIdForNonDestroy"
            disabled={isDisable}
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            value={parentFormData.needReasonableIdForNonDestroy}
            label="是否合理"
            onChange={handleChange}
          >
            <MenuItem value="1"></MenuItem>
            <MenuItem value="0"></MenuItem>
          </Select>
        </FormControl>
      </Grid>
      <Grid item xs={4}>
        {/* 直接设置对象值,不用handleChange */}
        <FormControl fullWidth>
          <InputLabel id="demo-simple-select-label">是否已确认</InputLabel>
          <Select
            disabled={isDisable}
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            name="planConfirmId"
            value={parentFormData.planConfirmId}
            label="是否已确认"
            onChange={(event) => {
              setFormData((prevValues: any) => {
                return {
                  ...prevValues,
                  planConfirmId: event.target.value,
                };
              });
            }}
          >
            <MenuItem value="1"></MenuItem>
            <MenuItem value="0"></MenuItem>
          </Select>
        </FormControl>
      </Grid>
    </Grid>
  );
});

export default ComponentsForm;

父组件

import { useEffect, useState, useCallback } from "react";
import ComponentsForm from "./SubForm";
import { Paper, TextField, Button, Grid } from "@mui/material";

const Customer = () => {
  const [scheduleDisable, setScheduleDisable] = useState(false);
  const [scheduleForm, setScheduleForm] = useState({
    needReasonableIdForNonDestroy: "",
    experimentProject: "",
    experimentWorkQuantity: "",
    planStartDate: "",
    planEndDate: "",
    autoGeneratePlan: "",
    autoGeneratePlanId: "",
    planConfirmId: "",
    planConfirm: "",
    checkboxValue: false,
    radioValue: "",
    option2: "",
  });

  const handleChildValuesChange = useCallback((val: any) => {
    setScheduleForm(val);
  }, []);

  const [num, setNum] = useState(1);

  useEffect(() => {
    console.log(scheduleForm);
  }, [scheduleForm]);

  useEffect(() => {
    console.log(num);
  }, [num]);

  return (
    <Paper>
      <div>
        {/* 验证 useCallback 是否有效*/}
        <Button
          variant="outlined"
          onClick={() => {
            setNum((val) => val + 1);
          }}
        >
          点击加工资
        </Button>
      </div>

      <ComponentsForm
        setFormData={handleChildValuesChange}
        parentFormData={scheduleForm}
        isDisable={scheduleDisable}
      />
      <Grid container spacing={2}>
        <Grid item xs={12}>
          <TextField
            fullWidth
            id="outlined-required"
            label="备注"
            value={scheduleForm.autoGeneratePlan}
            onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
              setScheduleForm({
                ...scheduleForm,
                autoGeneratePlan: event.target.value,
              });
            }}
          />
        </Grid>
      </Grid>
    </Paper>
  );
};

export default Customer;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前言如释重负,好用的技术就应该越来越简单React HooksReact 16.8 从提案转为正式加入的新特性。这个新特性是个非常棒的设计。 可以说对于React 技术栈的发展具分割线一样的意义。讲师在课程中提到:之前使用 React 作为主要的前端技术,开发一款网页游戏。在整个游戏的各个模块中,Redux ,mobx,以及蚂蚁金服的 ant-design,dva, umi 这些框架或者第三方库都有涉及使用。但是自从了解了Facebook官方提案的 Hooks 特性后,才真正觉得获得了前所未有的解脱。如果你有React开发经验,学习了解 Hooks 后,一有一种如释重负的轻松感。React 带来了方便也带来了迷茫相信关心 React Hooks 这项新特性的童鞋,很多已经有了一React 开发经验。那么你一有所体验,React 给我们带来方便的同时,也的确和长久以来的前端开发模式有极大的不同。React 并不需要用继承,而是推荐用嵌套。React 有独特的 jsx 语法。大多数情况 jsx 都使得我们的代码更加简洁了。然而有些时候也给我们带来了一些困扰。 比如数据的递,逻辑的复用。 react 是一种 mvvm 的设计模式,作为开发者一要清楚,那些数据是业务数据,那些数据是UI数据。否则你的代码很有可能会陷入混乱局面。大型项目中模块化与功能解耦困难在公司项目中 App 稍大的时候,我们发现状态提升和只通过 props 进行数据递。很多时候都很难实现我们的需求。这时无论我们是否清楚的了解,但是状态管理也就是 redux mobx 等,轻易地进入到了公司的项目中。我们经过初期的尝试发现状态管理,确实比用纯粹的 React 带来了数据递上的方便,以及代码组织上的清晰。但前提是你看懂且理解了 redux 大神晦涩的官网文档。 本来 React 被设计用来组件化前端开发。但当我们初期使用状态管理,我们常常会过度的使用状态数据,业务逻辑和ui逻辑没有清楚的分离,最终你的应用代码结果可能是:除了少数几个组件是独立的解耦的,大多数组件都因为状态数据的共享而耦合在了一起,且他们也完全依赖状态管理框架。无法再轻松的转移复用。使用高阶组件,属性渲染,渲染回调等高级特性,确实可以帮我们解决模块或功能的解耦问题。但是这些方法,确实有点超出普通“猿类”的技能。且降低了代码的可读性,对于团队协作,这是很致命的问题。React Hooks 真正开启前端模块化的金钥匙对于以上问题,React Hooks 都有很好的解决方案,官方的设计动机就是解决这些曾经的繁琐,化繁为简。React Hooks 让我们在纯函数中就可以使用 React 的众多特性。而不必使用类。代码扁平,易读。解耦状态相关逻辑,UI逻辑和业务逻辑更好的分离。这些逻辑往往是纯函数,而以前很容易混合在类组件中。通过自Hooks 我们可以把应用中“状态相关”逻辑解耦出来,独立编写到我们自己的hooks 中。从而更加易于复用和独立测试。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值