ReactJS need to conditionally display different onclick vs Link based on logic

*爱你&永不变心* 提交于 2020-01-06 06:59:54

问题


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

Without logic in the Render() const contents = this.state.data.map(item => (

This is the logic I'm struggling with

<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>

This WORKS from button class:

<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>   

Below is OLD code BEFORE changing to conditional , below is not code i want , for reference only.

onclick

<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 route redirect

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

回答1:


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>
)}

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" />



来源:https://stackoverflow.com/questions/58174810/reactjs-need-to-conditionally-display-different-onclick-vs-link-based-on-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!