diff --git a/package-lock.json b/package-lock.json index 167e089..8be3f0c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,6 +11,7 @@ "@testing-library/jest-dom": "^5.17.0", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", + "proptypes": "^1.1.0", "react": "^18.3.1", "react-dom": "^18.3.1", "react-scripts": "5.0.1", @@ -14521,6 +14522,11 @@ "resolved": "https://registry.npmmirror.com/react-is/-/react-is-16.13.1.tgz", "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" }, + "node_modules/proptypes": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/proptypes/-/proptypes-1.1.0.tgz", + "integrity": "sha512-589N0gHNvg6ocCDia1knxMwguEcZq1qyD8fVxFZEdZP0YKI+GTHyflsJH2mYE0YZbo1KNj5W8avdSR4iJDV+fw==" + }, "node_modules/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmmirror.com/proxy-addr/-/proxy-addr-2.0.7.tgz", diff --git a/package.json b/package.json index 4c47fac..de60657 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "@testing-library/jest-dom": "^5.17.0", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", + "proptypes": "^1.1.0", "react": "^18.3.1", "react-dom": "^18.3.1", "react-scripts": "5.0.1", diff --git a/src/App.js b/src/App.js index 053ef67..4fd1c40 100644 --- a/src/App.js +++ b/src/App.js @@ -212,7 +212,13 @@ function App() { justifyContent: 'center' }}> 父组件 - + SonComponent 插槽 slot2 (具名插槽)} + scopeslot={(scope)=>{return
{scope}
}}> +
+ SonComponent 插槽 slot1 +
+
diff --git a/src/components/SonComponent.js b/src/components/SonComponent.js index 095f067..8681d1d 100644 --- a/src/components/SonComponent.js +++ b/src/components/SonComponent.js @@ -1,4 +1,6 @@ import React from "react"; +import PropTypes from "proptypes" + export default class SonComponent extends React.PureComponent { state = { msg: "SonComponent Msg" @@ -19,17 +21,33 @@ export default class SonComponent extends React.PureComponent {
{this.props.msg} + +
+ {this.props.children} +
+ +
+ {this.props.slot2} +
+ +
+ {this.props.scopeslot(SonComponent 插槽 slot3 (作用域插槽) {this.state.msg})} +
} } SonComponent.propTypes = { - msg: (props)=>{ - if(typeof props.msg != "string"){ - throw new Error("msg 必须为 string 类型") - } - } + // 自定义类型校验 + // msg: (props)=>{ + // if(typeof props.msg != "string"){ + // throw new Error("msg 必须为 string 类型") + // } + // } + + // 使用 proptypes 提供的类型校验 + msg: PropTypes.string } SonComponent.defaultProps = {