自学内容网 自学内容网

【无标题】react组件封装

子组件制作

import { useState,useRef, useEffect} from "react"



const Table = (data)=> {

   const {value ,option} = data

   console.log(value)
   const [stata,setValue]  = useState()
   const  useRefs = useRef(value)


    useEffect(()=> {
        useRefs.current.value  = value 
    })
    const addGetvalue = () => {
       console.log(useRefs)
    }
    const table = ()=> {
           return <><input  ref={useRefs} onChange={(event)=> { 
            
            
            useRefs.current = event.target.value 
            option && option(event.target.value)

             }}/>4444444<button onClick={()=> {addGetvalue()}}> 初始化数据 </button></>
    }

    
    return  {table,addGetvalue}
}
export default Table

父组件制作

import logo from './logo.svg';
import './App.css';
import  tableaaa from './component/hooks/tableSwitch'
import { useRef ,useState} from 'react';
function App() {
  const {table,addGetvalue} = tableaaa({value:"llllll"})
  const newRef = useRef()
  const [state,setState] = useState()


  const text =  (changeValue)=> {
    const {table,addGetvalue} = tableaaa({value:"",option:changeValue})
    return table()
  }

  const changeValueOne = (value)=> {
      console.log("测试1事件",value)
  }
  const changeValueTow = (value)=> {
    console.log("测试2事件",value)
  }
  const changeValuethree = (value)=> {
  console.log("测试3事件",value)
  }
  const changeValuedao = (value)=> {
  console.log("测试4事件",value)
 }



  return (
    <div className="App">
      
         {table()}



         {text(changeValueOne)}
         {text(changeValueTow)}
         {text(changeValuethree)}
         {text(changeValuedao)}


        {/* <button onClick={()=> {addGetvalue()} }>kkkkkkkkkkkkkkkkkkkkkkkk</button> */}
    </div>
  );
}

export default App;

好处,每个组件都是独立的,子组件子负责样式的渲染,父组件子负责数据的处理维护

问题:项目过大,组件引用混乱,改动一处,好几处不能使用,这种组件之间的事件都是独立相互之间不会影响


原文地址:https://blog.csdn.net/qq_45623378/article/details/142934116

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!