3 回答
TA贡献1865条经验 获得超7个赞
我认为您是在询问如何将数据从孩子传递给父母。
您必须将一个方法从 App 传递给 Person。
并从 Person 组件调用该方法。
function Person (props){
const {setNameToApp} = props;
const name = "Jennifer";
// this useEffect is called when the component mounts for the first time
React.useEffect(()=>{
setNameToApp(name);
},[])
// I have also shown how to use button to change the greet state in the app.
return (
<div>
<button onClick={()=>{setNameToApp("name when I pressbutton")}}> Set Name </button>
</div>)
}
function App(props) {
const [greet, setGreet] = React.useState("");
// pass setGreet function to components which can call this and change the state of the greet
return (
<div>
<h1> Good {greet} </h1>
<Person setNameToApp = {setGreet} />
</div>
);
}
TA贡献1836条经验 获得超3个赞
将名称作为道具从 person.js(父组件)传递到 App.js(子组件)
Person.js
import React from 'react';
import App from './App'
export default function Person (){
const name="Jenifer"
return(
<div>
<App name={name}/>
</div>
);
}
应用程序.js
import { useState,useEffect } from 'react';
// import Person from './Person'
function App(props) {
const [greet, setGreeet] = useState("");
return (
<div className="App">
<h1> Good Morning {props.name} </h1> // Good Morning Jenifer
</div>
);
}
export default App;
添加回答
举报