Use of props in reactJs

0

I am learning react with official documentation, there in the tutorial of the official page develop a small example of the game tic tac toe and I understand it but there is a line that causes me a lot of confusion. In the square component (which represents a table on the game board) a value is received by parameter to fill it in with the props , which is send from parent board .

My confusion is in square is a button that makes use of the event onClick this is the code:

function Square(props) {
return (
  <button
    className="square"
     onClick={ props.onClick} >
    {props.value}
  </button>
);'}'

What does this mean onClick={props.onClick} ? What function does it call? or what is the function of props.onClick ?

    
asked by Jorge E. 19.07.2018 в 13:39
source

2 answers

0

the onClick is a synthetic event of react. When you pass the event handler (the function that is executed when you click)

<button
 className="square"
 onClick={ props.onClick} 
>
 {props.value}
</button>

You are passing the reference to the onClick function that passes from the parent component, it works exactly the same as a callback.

This is thanks to the fact that in javascript you can literally save a function in a variable or constant.

To be executed in a different scope or scope, the one that was declared.

In this case you are stored in the object of the properties of the compose Square The function called onClick that is declared in its parent component when the onClick event of the Square is activated is executed at that moment.

Example:

Class ComponentePadre extends Component {
  constructor(...props){
    super(...props);
    this.onClick = this.onCLick.bind(this);
  }

  //manajador onClick que se pasas como props
  onCLick(e){ 
    console.log(e)
  }
  render(){
    return(
    //almacenado la funcion en el componente hijo para ser ejecutada  dentro de el.
     <ComponenteHijo onClick={this.onClick}/>
    );
  }
}
    
answered by 19.07.2018 / 19:12
source
0

props is a variable that stores the parameters received in the tag:

<Square onClick={funcionQueTrataElClick} value="valor">

When you generate that <square> in the final HTML, it is replaced by the code that you return, something similar to:

<button className="square" onclick="funcionQueTrataElClick" value="valor">

    
answered by 19.07.2018 в 13:56