Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

275
Views
¿Cómo agregar condicionalmente o no hacer clic en un div en reaccionar?

Me gustaría saber si es posible configurar onClick en un elemento div para reaccionar en función del valor de una propiedad en mi caso canClick .

Soy consciente de que puedo verificar this.state directamente en el handler , en lugar de eso, estoy buscando una solución para implementar dentro del render .

 ... handler(){ } render() { const { canClick} = this.state return ( <div onClick={this.handler}>hello</div> ) } ...
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Pon la condición así:

 onClick={canClick ? this.handler : undefined }

Código de trabajo:

 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>

over 4 years ago · Santiago Trujillo Report

0

Puede tratar los atributos de los elementos (como onClick) como propiedades del objeto. Use el operador de propagación solo bajo condición, distribuya el onClick:

 <div {...(canClick && { onClick: this.handler })} > hello </div>
over 4 years ago · Santiago Trujillo Report

0

<div onClick={canClick ? this.handler : undefined} />

Si opta por un valor falso diferente en lugar de undefined en este ternario (es decir, false o null ), React (actualmente) arroja la siguiente advertencia:

"Si solía omitirlo condicionalmente con onClick={condición && valor}, pase onClick={condición ? valor: indefinido} en su lugar".

Editar 2020-01-05: solo false arroja el error anterior ( Reaccionar código fuente aquí ).

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!