我的应用程序的根目录是App
。我的 App
组件使用 react-router
路由到不同的页面。目前,我只有 1 个,但还会有更多。每个页面都会呈现父组件,父组件将有 2 个子组件。对于每个父组件,一个子组件(我们称之为 Child1
)是一种接受一些输入并进行 API 调用的表单。另一个组件(我们称之为 Child2
)将以表格形式呈现此数据。
我的目标:不同的 parent 将在不同的路线上呈现:/parent1
、/parent2
等。我希望Child1
呈现在在要在 /parent1?name=something
上呈现的 /parent1
和 Child2
上。查询参数需要保存用户提供的表单输入的值,以便我可以将其设为可共享的 URL。任何拥有这些参数的人都应该能够直接看到表格结果。我该怎么做?
这是我的一些精简代码:
App.js
:
const App = () => {
return(
<BrowserRouter>
<div>
<ul>
<li>
<Link to="/parent1">Parent-1</Link>
</li>
</ul>
</div>
<hr/>
<Switch>
<Route path="/parent1">
<Parent1 />
</Route>
</Switch>
</BrowserRouter>
);
};
Parent1.js
class Parent1 extends React.Component {
constructor(props) {
super(props);
this.state = {
products: [],
isSearched: false
};
};
onFiltersSelected = (products) => {
this.setState({
products: products,
isSearched: true
});
};
render() {
return (
<div>
<Header />
{!this.state.isSearched ?
<Child1 onFiltersSelected={this.onFiltersSelected} /> :
<Child2 products={this.state.products} />}
</div>
);
};
};
Child1.js
onFormSubmit = (e) => {
// make API call and call onFiltersSelected from Parent1
};
.......
render() {
return (
<div className="container container-fluid">
.........
.........
<div className="row">
<button type="submit" className="btn btn-primary">Search Instances</button>
</div>
</form>
</div>
);
};
Child2.js
class Child2 extends React.Component {
render() {
return (
<div className="container">
....
</div>
);
};
};
最佳答案
如果您定义 Parent1
的Route
喜欢 <Route path="/parent1" component={Parent1}/>
,React 会传递一些像 location
这样的 props 。你可以这样做props.location.name
并测试它。如果为空,则渲染 Child1
,如果没有,则渲染 Child2
.
来源:https://learnwithparam.com/blog/how-to-handle-query-params-in-react-router/
关于reactjs - 可以将新的/修改的 URL 添加到子组件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62561781/