[英]How to correctly pass a callback and a state to the Layout element in React Router Dom?
How to correctly pass callbacks and states to the Layout
so that they can be used elsewhere?如何正确地将回调和状态传递给
Layout
,以便它们可以在其他地方使用? When I share this as below, I have errors and a white screen:当我如下分享时,出现错误和白屏:
class Menu extends Component {
constructor(props) {
super(props);
this.onSearchF = this.onSearchF.bind(this)
}
state = {
searchBlock: false,
};
onSearchF = (keyword) => {
const filtered = this.state.data.filter((entry) =>
Object.values(entry).some(
(val) => typeof val === "string" && val.toLowerCase().includes(keyword.toLowerCase())
)
);
};
render() {
return (
<div className="content">
<Routes>
<Route path="/" element={<Layout searchBlock={this.state.searchBlock} onSearch={()=>this.onSearchF()}/>}>
<Route
index
element={
<Home data={this.state.data} num={this.state.data.length} />
}
/>
</Route>
</Routes>
</div>
);
}
}
export default Menu;
Here I pass the callback to the Header
that I previously passed to the Layout
:在这里,我将回调传递给之前传递给
Layout
的Header
:
const Layout = () => {
return (
<>
<Header sblock={this.props.searchBlock} onS = {this.props.onSearch}/>
</>
);
};
export default Layout;
I want to use the callback here:我想在这里使用回调:
function Header() {
return (
<header className="header">
<button onClick={()=>console.log(this.props.sblock)}>button</button>
</header>
);
}
export default Header;
Your Layout
is a functional component, and you are trying to use this.props
in it;你的
Layout
是一个功能组件,你试图在其中使用this.props
; this is incorrect.这是不正确的。 Get the
props
as part of arguments instead, like so:改为将
props
作为 arguments 的一部分获取,如下所示:
import { Outlet } from "react-router-dom";
const Layout = ({searchBlock,onSearch}) => {
return (
<>
<Header sblock={searchBlock} onS={onSearch}/>
<Outlet/>
</>
);
};
export default Layout;
Layout
component isn't accepting any props. Layout
组件不接受任何道具。Layout
component isn't rendering an Outlet
for nested routes. Layout
组件没有为嵌套路由呈现Outlet
。It seems that Layout
only exists to render the Header
component. Layout
似乎只存在于渲染Header
组件。 I'd suggest rendering Header
directly in the Main
component.我建议直接在
Main
组件中渲染Header
。
Example:例子:
class Menu extends Component {
state = {
data: [],
searchBlock: false,
};
onSearch = (keyword) => {
const filtered = this.state.data.filter((entry) =>
Object.values(entry).some((val) =>
typeof val === "string"
&& val.toLowerCase().includes(keyword.toLowerCase())
)
);
... do something with filtered ...
};
render() {
const { data, searchBlock } = this.state;
return (
<div className="content">
<Header sblock={searchBlock} onS={this.onSearch} />
<Routes>
<Route
path="/"
element={<Home data={data} num={data.length} />}
/>
</Routes>
</div>
);
}
}
export default Menu;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.