在React中,如何使锚点在点击时不执行任何操作? [英] In React, how can I cause anchors to do nothing on click?
本文介绍了在React中,如何使锚点在点击时不执行任何操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下html元素:
I have the following html element:
<a href onClick={() => fields.push()}>Add Email</a>
我需要href属性,以便引导程序使用链接样式(颜色,光标)对元素进行样式设置.
I need the href attribute so bootstrap styles the element with a link styling (color, cursor).
问题是,如果现在单击它,它将导致浏览器重定向.如何更新以上内容以不重定向浏览器onClick但仍运行fields.push()
?
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 事件中调用 preventDefault 函数,如下所示:
You should call preventDefault function from onClick event like this:
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>
...
)
这篇关于在React中,如何使锚点在点击时不执行任何操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文