首页 > 解决方案 > 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 />
  )
}

什么是提升工具栏内容或从兄弟组件传递这些内容的好方法?

标签: javascriptreactjs

解决方案


嗯,首先想到的是使用上下文 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 钩子中)。


推荐阅读