javascript - React 组件从另一个组件渲染子组件
问题描述
考虑以下 React 中简单 Web 应用程序的格式。该应用程序有一个底部工具栏,其中包含用于导航应用程序的按钮。按钮内容会根据您在应用程序中查看的页面而变化。
function App(props) {
return (
<div className="page">
<Switch>
<Route exact path="/">
<Homepage />
</Route>
<Route exact path="/login">
<Login />
</Route>
</Switch>
<Toolbar />
</div>
)
}
function Homepage(props) {
const nextButton = <a href="/login">Continue to login</a>
return (
<h1>Welcome</h1>
)
}
function Login(props) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const nextButton = <button onClick={()=> login(email, password)}>Login</button>
return (
<input type="email" onChange={e => setEmail(e.target.value)} />
<input type="password" onChange={e => setPassword(e.target.value)} />
)
}
function Toolbar(props) {
return (
<nextButton />
)
}
什么是提升工具栏内容或从兄弟组件传递这些内容的好方法?
解决方案
嗯,首先想到的是使用上下文 API。我们可以创建一个上下文,例如:
ToolbarContext
或其他东西。然后在该上下文中保留工具栏配置对象。
// context file
// Sample object ( this object will be set from another component by using context and setConfig method
// { url: '/', text: 'Continue to login'}
const [toolbarConfig, setConfig] = useState({});
// then as usual wrap the app in context provider and pass this `toolbarConfig` and the `setConfig` method down to all the components.
然后在Toolbar
组件内部从上下文同步数据。
之后,在每个组件中,当组件加载时,通过设置正确的 URL 和文本来更改上下文中的配置对象(这里的代码将在 useEffect 钩子中)。
推荐阅读
- ios - 应用重新打开时,Tableview 需要更多时间来显示数据
- marklogic - 服务器端 JavaScript (.sjs) 中的 Marklogic 光学查询获取作业失败
- ios - 连接到一个父目标的 Xcode 共享扩展如何断开连接并与另一个目标关联?
- r - gsub 用模式匹配代码而不是特定的字符串变量替换字符串
- ruby-on-rails - Rails:找不到没有 ID 的对象
- css - 填补 CSS 网格布局中的空白
- vue.js - vue.config.js 代理观察者套接字问题
- powershell - 如何关闭每个交互式 PowerShell 会话?
- sql - 在 DB2 中使用 MERGE 命令时出错
- c++ - 使用 detours 时防止递归挂钩