1

解决 react 项目控制台对 a 标签 使用了 href 属性(设置了值:javascript:;)的 warn...

 2 years ago
source link: https://hellodk.cn/post/131
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

解决 react 项目控制台对 a 标签 使用了 href 属性(设置了值:javascript:;)的 warning 问题

先看看 react blog, 看官方怎么说的
In React blog post:

URLs starting with javascript: are a dangerous attack surface because it’s easy to accidentally include unsanitized output in a tag like <a href> and create a security hole.

In React 16.9, this pattern continues to work, but it will log a warning. If you use javascript: URLs for logic, try to use React event handlers instead.

我们在使用 a 标签时,href属性可以用于指定超链接目标的 URL,其值可以使任何有效文档的相对的或绝对的 URL,包括片段标识符和 JavaScript 代码段。用户选择了 a 标签中的内容,浏览器会尝试检索并展示 href 属性指定的 url 所表示的文档,或者 执行 JavaScript 表达式、方法和函数的列表。
若用户不想用 a 标签的跳转能力时,而要使用自己绑定的 click 事件,往往会通过插入 js 代码段的方式,设置 href 值为javascript:;javascript:void(0) 以期达到 href 无跳转的效果。但是这样写代码会被 react 在控制台报如下错误:

console: A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed "javascript:;"

解决办法:属性值使用#或者#!

before:

<a href="javascript:;" onClick={() => this.handleComment(record, true)}>{intl.get('COMMON_MODIFY')}</a>

after modified:

<a href="#!" onClick={() => this.handleComment(record, true)}>{intl.get('COMMON_MODIFY')}</a>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK