React + Typescript - Reuse function of one component in another giving error

Asked

Viewed 63 times

0

Within a registration screen I have a pop-up to register a child record of the table in question.

I have a function that makes the pop-up appear and disappear on the "Cancel" button. I decided to assemble a separate component for this child and in research I found a way to assemble the scheme but it doesn’t seem to work.

The pop-up (which is being rendered in the child class) appears. But the problem is in the function that is not executed in the "Cancel button".

Here’s how’s the class son

interface IProps{
        action: () => void
 }

 export default class TelaCadastroAditivo extends React.Component<IProps,{}> 
 {
     render() {
     return (
        <div>
              <div className="col-md-3"> <button  onClick={() => 
                 this.props.action}>Cancelar</button></div>
          </div>
      );
   }
}

And here the father class

import TelaCadastroAditivo from '../DAO/TelaCadastroAditivo';

class AddFeed extends React.Component<ISpaFeedWebpartProps, {}>{
    constructor(props) {
       super(props)
    }
    public telaAditivo = () => {
        alert("Teste");
    }
    render() {
        return (
           <TelaCadastroAditivo  action={this.telaAditivo}/>
        );
    }
}
  • 1

    You’re not invoking the function, it should be onClick={() => this.props.action()} or onClick={this.props.action}. With onClick={() => this.props.action} you are just returning a reference to the function without invoking it.

  • @user140828 That’s right. Thank you very much.

No answers

Browser other questions tagged

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