首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无反应反应中的单页应用程序-路由器

无反应反应中的单页应用程序-路由器
EN

Stack Overflow用户
提问于 2022-09-14 10:18:52
回答 1查看 110关注 0票数 1

我正在尝试使用React构建我的第一个单一页面应用程序。我想在不使用任何外部库的情况下构建web应用程序,比如React。另外,我不知道这是否重要,但我使用的是对CDN的反应。

我很难找到如何在不同层次上隐藏和显示组件的反应。以下是应用程序的总体结构:

dashboard.html

代码语言:javascript
复制
...

<div id="content"> </div>

...

dashboard.js

代码语言:javascript
复制
document.addEventListener(
  "DOMContentLoaded",
  ReactDOM.render(<App />, document.querySelector("#content"))
);


function App() {
  return (
    <div>
      <AccountView />
      <PersonsView />
    </div>
  );
}

function AccountView() {
  return (
    <div>
      Foo
    </div>
  );
}

function PersonsView() {
  return (
    <div>
      <Persons />
      <AddPersonForm />
      <button id="showAccountView">Show Account View</button>
    </div>
  );
}

function Persons() {
  return (
    <div>
      Foo
    <button id="showAddPersonForm">Show Add Person Form</button>
    </div>
  );
}

function AddPersonsForm() {
  return (
    <form>
      Bar
    </form>
  );
}

<App />中,我只想显示<PersonsView />,只有单击按钮(#showAccountView)时,<PersonsView />才会被隐藏,<AccountView />才会显示出来。

然后在<PersonsView />中,我只想显示<Persons />,只有在单击按钮(#showAddPersonForm)时,<Persons />才会被隐藏,<AddPersonForm />才会显示出来。

EN

回答 1

Stack Overflow用户

发布于 2022-09-14 10:31:27

在App()中拥有状态可以处理组件的可见性。下面是一个未经测试的示例实现:

代码语言:javascript
复制
function App() {
    const [location, setLocation] = useState('AccountView');
    return (
        <div>
            {location === 'AccountView' && <AccountView />}
            {location === 'PersonsView' && <PersonsView />}
            <Button
                onPress={() => {
                    setLocation(
                        location === 'AccountView'
                            ? 'PersonsView'
                            : 'AccountView',
                    );
                }}
            />
        </div>
    );
}

您可以使用道具将setLocation函数传递给视图或为应用程序创建上下文

如何传递道具:

代码语言:javascript
复制
// call the account view like this
<AccountView setLocation={setLocation} />;

// and modify the account view like this
function AccountView({ setLocation }) {
    return (
        <div>
            <button onPress={() => setLocation('yourDestination')}>
                YourButtonText
            </button>
        </div>
    );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73715191

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档