react子傳父,與父傳子通訊方法
import { useState } from "react"; // 元件傳參 props是父元件傳過來的所以資料,props也是和vue一樣的不能修改 const SonComponent = (props) => { return ( <div> <h1>{props.title}</h1> <button onClick={()=>{props.cb() }}>點選{props.count}</button> {props.element} </div> ); }; // 當內容巢狀在子元件標籤內時,可以使用props.children獲取到內容 const SonComponent2 = (props) => { return ( <div> {props.children} </div> ); }; // 解構子元件傳過來的方法 const SonComponent3= ({onGetMsg,count}) => { const msg=count===0?'999':0 return ( <div> <button onClick={()=>{onGetMsg(msg)}}>點選</button> </div> ); }; function App() { const title="hello world"; const [count,setCount]=useState(0); return ( <div className="App"> {/*父傳子案例 */} <SonComponent title={title} count={count} cb={()=>{ alert('父元件方法')}} element={ <div>123</div>} /> <SonComponent2> <h2>類似於vue插槽</h2> </SonComponent2> {/* 子傳父案例 */} <h3>{count}</h3> <SonComponent3 onGetMsg={(e)=> setCount(e)} count={count}/> </div> ); } export default App;