Pass props to React grandson component

Asked

Viewed 94 times

-1

I have 3 components, Login, Loginpresentation and Cpfpresentation. Login is the component where I contain all the logic and that call the respective "... Presentation", Login and Cpf Presentation are where all the HTML code is actually.

What’s the matter ?

I have a "test()" function in the Login component and I want to pass it there to Cpfpresentation, which structure??

Login calls Loginpresentation and Loginpresentation calls Cpfpresentation. Then Login is grandfather of Cpfpresentation. So I did so:

Login.js

export default class Login {
   teste() {
      console.log('Teste');
   }

   render() {
      return(
         <div>
            <LoginPresentation 
               teste={this.teste}
            />
         </div>
      )
   }
}
LoginPresentation.jsx

export default function LoginPresentation(props) {
   return(
      <div>
         <CpfPresentation
            teste={props.teste}
         />
      </div>
   )
}
CpfPresentation.jsx

export default funciton CpfPresentation(props) {
   return(
      <div>
         <button type="button" onClick={ () => props.teste() }>
            Executar
         </button>
      </div>
   )
}

But I click and nothing happens, if I create the same button in Loginpresentation, it works perfectly, someone can tell me what I’m doing wrong?

  • this.teste.bind(this) in the component Login.

  • Best way to share properties this way would be using hook "useContext" https://pt-br.reactjs.org/docs/hooks-reference.html#usecontext

  • The solution of bind(this) didn’t work. In Loginpresentation the function works, so the error is not when moving from Login.js to Loginpresentation.jsx, but from Loginpresentation.jsx to Cpfpresentation.jsx

1 answer

0


You should not run it on the button, because function is based on memory reference, so your cpfPresentation should be as follows:

CpfPresentation.jsx

export default funciton CpfPresentation(props) {
   return(
      <div>
         <button type="button" onClick={props.teste}>
            Executar
         </button>
      </div>
   )
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.