ReactJS需要根据逻辑有条件地显示不同的onclick与Link [英] ReactJS need to conditionally display different onclick vs Link based on logic

查看:426
本文介绍了ReactJS需要根据逻辑有条件地显示不同的onclick与Link的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标,我可以通过onclick与route来显示不同的HTML

Goal I have it to display different HTML with onclick vs. route

Render()const contents = this.state.data.map(item => (

这是我一直在努力的逻辑

<button id={item.Member_ID} type="button"
  {` ${this.isExist(item.Member_ID) ? <Link to='surveysai/'>
      <button type="button" className='btn btn-success'>SAI</button>  </Link>             
    : ${onClick={(e) => this.downloadUser(item.Member_ID, e)}}`}
    className={`btn ${this.isExist(item.Member_ID) ? "btn-success" : "btn-warning"}`} > {this.isExist(item.Member_ID) ? "SAI" : "Ready for Download"}</button>

按钮类的工作原理:

<button id={item.Member_ID} type="button"
 className={`btn ${this.isExist(item.Member_ID) ? "btn-success" : "btn-warning"}`} > {this.isExist(item.Member_ID) ? "SAI" : "Ready for Download"}</button>   

下面是变为条件代码之前的OLD代码,下面不是我想要的代码,仅供参考.

点击

<button id={item.Member_ID} type="button" onClick={(e) => this.downloadUser(item.Member_ID,e)} 
      className={() => this.checkItem(item.Member_ID)}>Ready for Download</button>

链接路由重定向

<Link to='surveysai/'>
    <button type="button" className="btn btn-success">SAI</button>                   
</Link>

推荐答案

为什么不有条件地渲染Link或按钮.

Why don't you conditionally render either the Link or the button.

{this.isExist(item.Member_ID) ? (
  <Link to='surveysai/'>
      <button type="button" className='btn btn-success'>SAI</button>  
  </Link>
) : (
  <button 
    onClick={(e) => this.downloadUser(item.Member_ID, e)}
    className={`btn ${this.isExist(item.Member_ID) ? "btn-success" : "btn-warning"}`}> {this.isExist(item.Member_ID) ? "SAI" : "Ready for Download"} . 
  </button>
)}

此外,假设这是一个React Router Link组件,您实际上不需要在Link内部呈现按钮.您可以将类名作为道具传递,例如:

Also, you don't actually need to render a button inside of a Link, assuming this is a React Router Link component. You can just pass classnames as props like:

<Link to="/wherever" className="btn btn-success" />

这篇关于ReactJS需要根据逻辑有条件地显示不同的onclick与Link的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆