1.父子传值、插槽都是基于props
2.在react里父组件给组件传值跟具名插槽并无区别
3.子组件给父组件传值,也是利用props上定义方法,子组件拿到这个方法并传值
4.默认插槽,在子组件通过props.children获取
5.作用域插槽是通过父组件定义一个方法执行,子组件拿到这个方法并传值
import styles from './index.less'; import React from 'react'; import Son from './components/son' import { useState } from 'react' let data = { a: 'props参数', b: <div>我是具名插槽</div> } function defaultCc() { return <div>我是默认插槽</div> } function handleEmit(val: string) { console.log(val) } const HomePage: React.FC = () => { class Cc extends React.Component { state = { ...data } render() { return <div> <h3>class组件</h3> <Son a={this.state.a} b={this.state.b} scopeslot={(scope) => // (<div>{scope.name}</div>) ( scope.map((item, index) => { return <div key={index}>作用域插槽:{item.name}</div> }) ) } handleEmit={handleEmit}> {defaultCc()} </Son> </div> } } let [a, setA] = useState(data.a) let [b, setB] = useState(data.b) return ( <div className={styles.container}> <h2>props和插槽</h2> <h3>函数组件</h3> <Son a={a} b={b} scopeslot={(scope) => // (<div>{scope.name}</div>) ( scope.map((item, index) => { return <div key={index}>作用域插槽:{item.name}</div> }) ) } handleEmit={handleEmit}> {defaultCc()} </Son> <Cc></Cc> </div> ); }; export default HomePage;
import { Button } from 'antd'; import { useState } from 'react' interface MyObject { name: string; } interface Props { a: string; b: React.ReactNode; children?: React.ReactNode; scopeslot?: (scope: MyObject[]) => React.ReactNode; handleEmit: (param: string) => void; } const Son: React.FC<Props> = (props) => { console.log(props) let [msg, setMsg] = useState([{ name: '1', }, { name: '2', }, { name: '3', }]) return <div> <Button type="primary" size="small">son组件</Button> <div>{props.a}</div> <div>{props.children}</div> <div>{props.b}</div> <div>{props.scopeslot?.(msg)}</div> <Button type="primary" size="small" onClick={() => { props.handleEmit('给父组件传值') }}>给父组件传值</Button> </div> }; export default Son;
标签:name,插槽,React,handleEmit,props,组件 From: https://www.cnblogs.com/ssszjh/p/18118746