【问题标题】:ReactJS: Use Link in props instead of a-tagReactJS:在道具中使用链接而不是标签
【发布时间】:2018-12-10 10:02:54
【问题描述】:

当 API 向前端发送错误时,我想使用 react-router-dom 内部的 react-router-dom 组件中的 Link 而不是 a-tag。这可能吗?

React 中的代码:

{
    errors.activateAccount && (
        <div className="invalid-feedback" dangerouslySetInnerHTML={{__html: 
    errors.activateAccount}}/>
     )
}

来自 API 的响应:

if (!user.activated) {
  errors.activateAccount = 'Here comes the error message with a <a href="/">link</a>.';
  return res.status(400).send(errors);
}

【问题讨论】:

  • 您能否在 codepen 或 jsFiddle 中复制您的组件。

标签: reactjs react-router react-router-dom


【解决方案1】:

在我看来,通过后端执行此操作不是一个好选择,您可以简单地传递一条消息并处理它在前端应用程序中的外观,在这种情况下,使用 React。

来自 API 的响应:

if (!user.activated) {
  errors.activateAccount = 'Simple Message';
  return res.status(400).send(errors);
}

在 React App 中,您可以获取响应并在您的组件中执行此操作。

// inside render() Method
render() {
  if(errors.activateAccount.length > 0){
    // Now you return the message composed in Link Component.
    return <Link>{errors.activateAccount.message}</Link>
  } else {
    // Now you return your default component or anything you want
  }
}

【讨论】:

  • 看起来不错,但我认为它不适用于我的情况。问题是,来自 api 的错误消息在文本中有一个链接。只是其中的一部分。
  • 我们可以开发一个函数来从消息中提取链接。
  • 对于您的示例响应,'Here comes the error message with a &lt;a href="/"&gt;link&lt;/a&gt;.'.split(`&lt;a href="`)[1].split(`"&gt;`)[0]; 此代码可以提取位于a-taghref 属性中的链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-05
  • 1970-01-01
  • 2020-11-16
相关资源
最近更新 更多