会vue,学习react组件父子通信
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;
本文来自博客园,作者:三线码工,转载请注明原文链接:https://www.cnblogs.com/shangrao/p/18219385