身为react初学者,遇到这个问题记录一下,在代码编译器里面可以直接运行,不会存在一点报错,测试了很多遍了,
就不放gif图片了
效果展示:可能不是特别明显
如上图所示
下方是全部代码
1. import React, { useEffect, useState } from "react"; 2. import { Stepper, Checkbox } from "react-vant"; 3. function calculateTotalQuantity(cart) { 4. let totalQuantity = 0; 5. for (let item of cart) { 6. totalQuantity += item.num; 7. } 8. return totalQuantity; 9. } 10. export default function App() { 11. const [list, setList] = useState([ 12. { name: "上官二" }, 13. { name: "张三" }, 14. { name: "李四" }, 15. { name: "王五" }, 16. { name: "赵六" }, 17. { name: "李七" }, 18. { name: "真的是" }, 19. ]); 20. const [allChecked, setAllChecked] = useState(false); 21. // useEffect(() => { 22. // // render() 23. // }, []); 24. useEffect(() => { 25. if (list.length === list.filter((item) => item.checked).length) { 26. setAllChecked(true); 27. } else { 28. setAllChecked(false); 29. } 30. }, [list]); 31. 32. useEffect(() => { 33. if (allChecked) { 34. setList( 35. list.map((item) => { 36. item.checked = true; 37. return item; 38. }) 39. ); 40. } else { 41. setList( 42. list.map((item) => { 43. item.checked = false; 44. return item; 45. }) 46. ); 47. } 48. }, [allChecked]); 49. return ( 50. <div> 51. {list.map((item, index) => ( 52. <div key={item.id}> 53. <div style={{ display: "flex" }}> 54. <Checkbox 55. checked={item.checked} 56. onChange={(checked) => { 57. setList(() => { 58. let arr = [...list]; 59. arr[index].checked = checked; 60. return arr; 61. }); 62. }} 63. /> 64. <div> 65. <p>{item.name}</p> 66. </div> 67. </div> 68. </div> 69. ))} 70. <div> 71. <Checkbox 72. checked={allChecked} 73. onChange={setAllChecked} 74. style={{ background: "white" }} 75. /> 76. </div> 77. </div> 78. ); 79. }