7. 父子组件传值

This commit is contained in:
shikong 2024-10-26 15:20:53 +08:00
parent e13c5669ed
commit 3ae520074a
Signed by: Shikong
GPG Key ID: BD85FF18B373C341
3 changed files with 62 additions and 9 deletions

View File

@ -1,9 +1,10 @@
import React from "react";
import React, {useState} from "react";
// import logo from './logo.svg';
import './App.css';
import InputComponent from "./components/InputComponent";
import SonComponent from "./components/SonComponent";
import SonComponent2 from "./components/SonComponent2";
function App() {
// vue3 组合式 API
@ -29,7 +30,8 @@ function App() {
this.state = {
a: 0,
arr: [0, 1, 2]
arr: [0, 1, 2],
msg: "parent msg"
}
}
@ -159,6 +161,13 @@ function App() {
}
}
const [msg,setMsg] = useState("parent msg")
const changeMsg = (newMsg) => {
setMsg(newMsg)
return msg;
}
return (
<div className="App">
<header className="App-header">
@ -219,6 +228,8 @@ function App() {
SonComponent 插槽 slot1
</div>
</SonComponent>
<SonComponent2 msg={msg} changeMsg={changeMsg}></SonComponent2>
</div>
</header>
</div>

View File

@ -31,7 +31,12 @@ export default class SonComponent extends React.PureComponent {
</div>
<div style={{margin: 'auto', border: '1px solid', width: '90%', overflow: 'auto'}}>
{this.props.scopeslot(<span>SonComponent 插槽 slot3 (作用域插槽) {this.state.msg}</span>)}
{this.props.scopeslot(<div>
<div>SonComponent 插槽 slot3 (作用域插槽)</div>
<div>
{this.state.msg}
</div>
</div>)}
</div>
</div>
</div>

View File

@ -1,13 +1,50 @@
import React, {useState} from "react";
export default function SonComponent2(props){
const [state] = useState({
msg: ""
import React, {useEffect, useState} from "react";
export default function SonComponent2(props= {
msg:"",
changeMsg:(_)=>{}
}){
const [state, setState] = useState({
msg: "son msg",
tmp: "",
count: 0,
})
function changeMsg(){
let target = `parent msg 被修改 (${++state.count})`
setState({
...state,
tmp: props.changeMsg(target)
})
}
function revokeChangeMsg(){
setState({
...state,
// count: state.count > 0 ? --state.count : 0,
tmp: props.changeMsg(state.tmp)
})
}
return <div style={{border: '1px solid', width: '80%', overflow: 'auto'}}>
子组件
{state.msg}
子组件2
<div style={{border: '1px solid', width: '80%', overflow: 'auto', margin: 'auto'}}>
<div>
{state.msg}
</div>
<hr/>
<div>
{props.msg}
<div>
<button onClick={changeMsg}>修改msg</button>
<button onClick={revokeChangeMsg}>撤销操作</button>
</div>
</div>
</div>
</div>
}