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 命名 组件
@ -53,16 +55,16 @@ function App() {
console.log("setState 之外, 获取不到修改后的值 => ", this.state.a)
}
addArr = ()=>{
this.setState((state)=>{
state.arr.push(state.arr[state.arr.length - 1 ] + 1)
addArr = () => {
this.setState((state) => {
state.arr.push(state.arr[state.arr.length - 1] + 1)
return {
...state,
// 解构赋值 使其地址改变 才能触发视图更新
// 不直接操作原对象, 要 先拷贝 再操作
arr: [...state.arr],
}
}, ()=>{
}, () => {
console.log("state.arr => ", this.state.arr)
})
}
@ -122,21 +124,21 @@ function App() {
show: true
}
show = ()=>{
this.setState((state)=>({
show = () => {
this.setState((state) => ({
...state,
show: true
}))
}
hide = ()=>{
this.setState((state)=>({
hide = () => {
this.setState((state) => ({
...state,
show: false
}))
}
render(){
render() {
return <div style={{border: '1px solid', width: '80%', overflow: 'auto'}}>
<div>条件渲染</div>
@ -146,12 +148,13 @@ function App() {
<button onClick={this.hide}>隐藏</button>
<button onClick={this.show}>显示</button>
</div>
<button onClick={()=>{
this.setState((state)=>({
<button onClick={() => {
this.setState((state) => ({
...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>
}