twitter-bootstrap 在 React 中,如何使锚点在点击时不执行任何操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44838477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In React, how can I cause anchors to do nothing on click?
提问by AnApprentice
I have the following html element:
我有以下 html 元素:
<a href onClick={() => fields.push()}>Add Email</a>
I need the href attribute so bootstrap styles the element with a link styling (color, cursor).
我需要 href 属性,因此引导程序使用链接样式(颜色、光标)为元素设置样式。
Problem is, if I click that now it causes the browser to redirect. How can I update the above to not redirect the browser onClick but still run fields.push()?
问题是,如果我现在点击它会导致浏览器重定向。如何更新上述内容以不重定向浏览器 onClick 但仍然运行fields.push()?
回答by Ritesh Bansal
You should call preventDefaultfunction from onClickevent like this:
您应该像这样从onClick事件调用preventDefault函数:
class App extends React.Component {
onClick = (e) => {
e.preventDefault()
console.log('onclick..')
}
render() {
return (
<a href onClick={this.onClick} >Click me</a>
)
}
}
You can use something like this particular to your use case:
您可以在您的用例中使用类似这样的东西:
const renderEmails = ({ fields }) => (
...
<a href onClick={(e) => {
e.preventDefault()
fields.push()
}}>Add Email</a>
...
)
回答by Vectrobyte
Here's a simple solution,
这是一个简单的解决方案,
- On React class component
- 在 React 类组件上
class App extends React.Component {
onClick() {
console.log('onclick..')
}
render() {
return (
<a href={void(0)} onClick={this.onClick} >Click me</a>
)
}
}
React is dropping the
javascript:void(0)solution and the href doesn't certainly accept the empty attribute value.
React 正在放弃
javascript:void(0)解决方案,并且 href 肯定不接受空属性值。
Basically what react wants us to do is to use a different component, for instance a button. We can always make a button look like a link using CSS(and thus, won't contain hrefand the complexity to remove it's behaviour). So, instead of using an anchor tag as a button, use the button element itself. Hope it makes sense.
基本上 React 希望我们做的是使用不同的组件,例如按钮。我们总是可以使用 CSS 使按钮看起来像一个链接(因此,不会包含href和删除它的行为的复杂性)。因此,不要使用锚标记作为按钮,而是使用按钮元素本身。希望这是有道理的。
回答by Jan Cio?ek
You should consider write method clickHappens in react component instead of writing this inline. Hope it works!
您应该考虑在 react 组件中编写方法 clickHappens 而不是编写此内联方法。希望它有效!
<a href onClick={(e) => {e.preventDefault(); fields.push()}}> Add Email </a>
回答by Ashu
add javscript:void(0):
添加 javascript:void(0):
<a href="javascript:void(0);" onClick={() => fields.push()}>Add Email</a>
回答by SatishBorkar
fields.push()}>Add Email
fields.push()}>添加电子邮件
In TypeScript href="javascript:void(0);"throws warning, so there any other way to skip that warnings
在 TypeScript 中href="javascript:void(0);"会抛出警告,因此还有其他方法可以跳过该警告
回答by Peter Yarama Ndirpaya
try the following code snippet
试试下面的代码片段
<a href="true" ....>

