How to conditionally add or not onClick on a div in react?

前端 未结 6 1362
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 02:26

I would like to know if it is possible to set onClick on a div element in react based on the value of a property in my case canClick.

I am awar

相关标签:
6条回答
  • 2021-02-01 02:35

    This is how I would do it:

    onClick={(canClick && this.handler) || null}
    
    0 讨论(0)
  • 2021-02-01 02:36

    Yes you can with ternaru operator, which evaluates the left side as boolean and if true it executes the right side or the fallback.

    <div onClick={() => canClick ? this.handler() : () => false }>hello</div>
    

    https://stackblitz.com/edit/react-uwzn4n

    0 讨论(0)
  • 2021-02-01 02:44

    You can treat the elements attributes (like onClick) as object properties. Use the spread operator to only on condition, spread the onClick:

    <div
      {...(canClick && { onClick: this.handler })}
    >
      hello
    </div>
    
    0 讨论(0)
  • 2021-02-01 02:52

    You can add Conditional Operator for this kind of purpose.

    handler(){
    }
    render() {
      const { canClick} = this.state
      return (
          <div>
           {
            (canClick) ? 
             (<div onClick={this.handler}>clickble</div>) : 
             (<div>not clickble</div>)
            }
          </div>
    
      )
    }
    

    Here is document example for that reactjs.org/docs/conditional-rendering

    0 讨论(0)
  • 2021-02-01 02:58
    <div onClick={canClick ? this.handler : undefined} />
    

    If you opt for a different falsy value instead of undefined in this ternary (i.e. false or null) React (currently) throws the following warning:

    "If you used to conditionally omit it with onClick={condition && value}, pass onClick={condition ? value : undefined} instead."

    Edit 2020-01-05: only false throws the above error (React source code here).

    0 讨论(0)
  • 2021-02-01 03:00

    Put the condition like this:

    onClick={canClick ? this.handler : undefined }
    

    Working Code:

    class App extends React.Component {
      
       _click(){
          // it will not print the value
          console.log('yes');
       }
    
       render(){
          return (
            <div>
              <div onClick={false ? this._click : undefined }>Click</div>
            </div>
          )
       }
    }
    
    ReactDOM.render(<App />, document.body);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

    0 讨论(0)
提交回复
热议问题