简体   繁体   English

如何从按钮单击加载组件?

[英]How to load a component from a button click in react?

I'm creating a simple react app.我正在创建一个简单的反应应用程序。 I need to load a component from a button click.我需要通过单击按钮加载组件。 When I click the edit button I need to load the edit component.当我单击edit按钮时,我需要加载编辑组件。 I tried it using <Link> .我尝试使用<Link> But I can't understand how to give the relative path.但我不明白如何给出相对路径。 It means it need to load it like http://localhost:3002/viewTicket/603c9a02a2ccd501f45f820e/edit .这意味着它需要像http://localhost:3002/viewTicket/603c9a02a2ccd501f45f820e/edit一样加载它。 I need to load it from http://localhost:3002/viewTicket/603c9a02a2ccd501f45f820e .我需要从http://localhost:3002/viewTicket/603c9a02a2ccd501f45f820e加载它。 How can I give the relative path?我怎样才能给出相对路径?

App.js应用程序.js

<Provider store={configureStore()}>
      <BrowserRouter>
        <div className="App">
          <LayoutWrapper>
            <Switch>
              <Route path="/" exact component={Home} />
              <Route path="/viewTicket/:id" exact component={ViewTicket} />
              <Route path="/viewTicket/:id/edit" exact component={EditTicket} />
            </Switch>
          </LayoutWrapper>
        </div>
      </BrowserRouter>
    </Provider>

Ticket.js票务.js

                       <Link to="/viewTicket/:id/edit">
                          <Button size="lg" onClick={this.handleEdit}>
                            <Pencil />
                            &nbsp; Edit
                          </Button>
                        </Link>

在此处输入图像描述 But url lokks like this.但是 url 喜欢这样。 Is there any other way to do this?有没有其他方法可以做到这一点?

You forgot to include the actual ID in the URL.您忘记在 URL 中包含实际 ID。 You're just directing the user to this literal string that has ":id" in it:您只是将用户定向到其中包含“:id”的文字字符串:

<Link to="/viewTicket/:id/edit">

Whatever your ID values is (for demonstration let's assume it's in a variable called id ), you'd use that to build your URL:无论您的 ID 值是什么(为了演示,我们假设它位于一个名为id的变量中),您将使用它来构建您的 URL:

<Link to={`/viewTicket/${id}/edit`}>

As an aside, this is a very strange structure and will likely lead to confusion:顺便说一句,这是一个非常奇怪的结构,可能会导致混淆:

<Link to="/viewTicket/:id/edit">
  <Button size="lg" onClick={this.handleEdit}>

Putting a button inside of a link means that you're trying to simultaneously do two different things.在链接中放置一个按钮意味着您正在尝试同时做两件不同的事情。 Should this.handleEdit be invoked?应该调用this.handleEdit吗? Or should the user be redirected by the link?还是应该通过链接重定向用户? It's best to invoke a single operation.最好调用单个操作。 If some logic needs to happen inside of this.handleEdit before redirecting the user, then remove the <Link> and manually redirect the user (likely using the useHistory hook) after performing that logic.如果在重定向用户之前需要在this.handleEdit内部发生某些逻辑,则删除<Link>并在执行该逻辑后手动重定向用户(可能使用useHistory挂钩)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM