如何在React中将数据从一个子级传递给另一个子级(嵌套在主页中)



我很难弄清楚如何将搜索词ChildOne传递到ChildTwo(嵌套在页面中(。我希望我在下面提供的所有代码都能让它变得清晰。我试图将状态提升到App.js组件,但它不起作用,或者可能我做得不对。如果有任何帮助,我将不胜感激。提前感谢:(

儿童1:

const ChildOne = () => {
const [searhTerm, setSearchTerm] = useState("");

return(
<InputContainer>
<input
type="text"
placeholder="Find a recipe"
value={searchTerm}
onChange={(e) => {
setSearchTerm(e.target.value);
}}
/>
<SearchIcon />
</InputContainer>
)
}

儿童2:

const ChildTwo = () => {

// I want to pass the searchTerm to be used in a fetch request in this component 
const apiURL = `'url' + {searchTerm}`;

return(
...
)
}

App.js

function App(){
return(
<>
<ChildOne/>
<Switch>
<Route path="/" exact component={Home}/>
<Switch/>
</>
)
}

Home.js:

const Home = () => {
return (
<>
<ChildTwo />
</>
);
};

有几种方法可以做到这一点。。。我建议你使用上下文Api。如果您不想使用上下文Api或状态管理

参见以下示例

在此处输入链接描述

import { useState } from "react";
import {
Route,
Switch,
BrowserRouter as Router,
RouterProps
} from "react-router-dom";
import ChildOne from "./ChildOne";
import Home from "./Home";
function App() {
const [value, setValue] = useState("");
return (
<>
<ChildOne setValue={setValue} />
<Router>
<Switch>
<Route path="/" exact>
<Home value={value} />
</Route>
</Switch>
</Router>
</>
);
}
export default App;

相关内容

最新更新