【问题标题】:How to change the url dinamically when redirecting on click? React重定向onclick时如何动态更改url?反应
【发布时间】:2021-06-29 08:38:13
【问题描述】:

如何动态地更改网址?这个 url 'www.example.com' 会根据我使用它的位置而变化,如下所示,查询字符串也会根据组件和卡 ID 发生变化。

这是我的代码的简单示例:

return (
props.news.map((content, index) =>
<NewsCard 
key={index}
title={content.title}
text={content.text}
onClick={() => {
location.href = 'www.example-news.com/?a=query';
}}
/>
<JurnalistCard
key={index}
person={content.person}
name={content.name}
onClick={() => {
location.href = 'www.example-jurnaist.com/?a=query';
}}/>
))

Json 文件:

export const news: News[] = [
  {
        title: 'Title1',
        text: 'Text test',
        queryString1: 'queryString',
        queryString2: 'queryString',
        person: 'Full Name',
        name: 'John'
  },
 {
        title: 'Title1',
        text: 'Text test',
        queryString1: 'queryString',
        queryString2: 'queryString',
        person: 'Full Name',
        name: 'John'
  },
 {
        title: 'Title1',
        text: 'Text test',
        queryString1: 'queryString',
        queryString2: 'queryString',
        person: 'Full Name',
        name: 'John'
  }
]

我是 React 新手,请帮忙。

【问题讨论】:

  • location.hreflocation.replace 应该可以工作。请参阅docs。你的代码有什么问题?

标签: reactjs typescript redirect react-router query-string


【解决方案1】:

您可以在 props 中发送 url 并执行类似的操作

return (
    props.news.map((content, index) =>
    <NewsCard 
        key={index}
        title={content.title}
        text-{content.text}
        onClick={() => {
            location.href = content.newsUrl;
        }}
     />
     <JurnalistCard
         key={index}
         person={content.person}
         name={content.name}
         onClick={() => {
             location.href = content.journalistUrl;
     }}/>
 ))

如果您无法将 url 存储在 props 中并且您使用其他值来形成查询,您可以这样构造它:

{"'www.example-news.com/?a=" + content.title}

【讨论】:

  • 我已经尝试过了,但它没有从 json 中读取记者Url,而是读取了内容,但是在点名记者Url 给出任何内容并且不返回字符串之后。
  • 你的 json 文件是什么样的?
  • 这可能与json无关。试试 window.location.href
  • 我在描述中添加了json
  • 我解决了这个问题。我不知道为什么,但它只有在反引号 ${content.journalistUrl} 中才有效,而不是像这样 {content.journalistUrl}
猜你喜欢
  • 2018-12-25
  • 2021-08-06
  • 1970-01-01
  • 2017-06-21
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 2018-11-11
相关资源
最近更新 更多