本文介绍了在 React 中,如何使锚点在点击时不执行任何操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号..我有以下 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屋!
更多推荐
[db:关键词]
发布评论