7. props 属性

This commit is contained in:
shikong 2024-10-26 13:39:09 +08:00
parent 2773535e9d
commit c70b581393
Signed by: Shikong
GPG Key ID: BD85FF18B373C341
3 changed files with 78 additions and 12 deletions

View File

@ -3,6 +3,8 @@ import React from "react";
import './App.css';
import InputComponent from "./components/InputComponent";
import SonComponent from "./components/SonComponent";
function App() {
// vue3 组合式 API
// React 必须大写 Pascal 命名 组件
@ -151,7 +153,8 @@ function App() {
...state,
show: !state.show
}))
}}>切换</button>
}}>切换
</button>
</div>
}
}
@ -198,6 +201,19 @@ function App() {
<IfComponent/>
<InputComponent/>
<div style={{
border: '1px solid',
width: '80%',
overflow: 'auto',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center'
}}>
父组件
<SonComponent a={1} b={2} msg={"App Msg"}/>
</div>
</header>
</div>
);

View File

@ -0,0 +1,37 @@
import React from "react";
export default class SonComponent extends React.PureComponent {
state = {
msg: "SonComponent Msg"
}
// constructor(props) {
// super(props);
// console.log(props)
// }
render() {
return <div style={{border: '1px solid', width: '80%', overflow: 'auto'}}>
子组件
<div>
{this.state.msg}
</div>
<div>
{this.props.msg}
</div>
</div>
}
}
SonComponent.propTypes = {
msg: (props)=>{
if(typeof props.msg != "string"){
throw new Error("msg 必须为 string 类型")
}
}
}
SonComponent.defaultProps = {
msg: "defaultProps"
}

View File

@ -0,0 +1,13 @@
import React, {useState} from "react";
export default function SonComponent2(props){
const [state] = useState({
msg: ""
})
return <div style={{border: '1px solid', width: '80%', overflow: 'auto'}}>
子组件
{state.msg}
</div>
}