Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
Trigger onClick function from within conditional content

I'm using the following code. Inside the ContentTwo component, there is a button, I want it to be able to trigger the same function as the button in the render, when it is the live content. How would I go about this?

class Toggle extends React.Component {
   constructor(props) {
     super(props);
     this.state = {isToggleOn: true};

      // This binding is necessary to make `this` work in the callback
     this.handleClick = this.handleClick.bind(this);
     }

   handleClick() {
       this.setState(prevState => ({
              isToggleOn: !prevState.isToggleOn
       }));
    }

    render() {
        return (
             <div >
                 {this.state.isToggleOn ? <ContentOne /> : <ContentTwo />}
                 <button onClick={this.handleClick}>Swap</button>
             </div>
         );
     }
     }
     function ContentOne(props) {
         return(<h1>Content One</h1>
          );
     }

     function ContentTwo(props) {
          return(<button onClick={this.handleClick}>Swap like the other button</button>
          );
     }

      ReactDOM.render(
             <Toggle />,
             document.getElementById('root')
      );
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could pass the this.handleClick to ContentTwo and access it from the props:

 <ContentTwo handleClick={this.handleCLick} />

and then

 function ContentTwo(props) {
      return(<button onClick={props.handleClick}>Swap like the other button</button>
      );
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda