If you want to access the props of a component within a function defined within it (such as handleAdd
), you don’t need to use this
or even pass them as argument. You can access them normally, using the scope of Javascript, which allows you to access variables of the upper scope.
Thus:
import React from 'react';
import PageHeader from '../template/PageHeader';
import Forms from '../componentes/Forms';
import List from '../componentes/List';
function Todo(props) {
function handleAdd() {
console.log(props);
}
return (
<div>
<PageHeader name='Tarefas ' small='Cadastro'></PageHeader>
<Forms handleAdd={handleAdd}></Forms>
<List></List>
</div>
);
};
export default Todo;
See a similar example working:
function Form(props) {
return (
<button onClick={props.onClick}>Clique-me!</button>
);
}
function Todo(props) {
function handleClick() {
console.log(props);
}
return (
<div>
<span>{props.todo}</span>
<Form onClick={handleClick} />
</div>
);
}
ReactDOM.render(
<React.Fragment>
<Todo todo="Foo" />
<Todo todo="Bar" />
<Todo todo="Baz" />
</React.Fragment>,
document.querySelector('#app')
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="app"></div>
Note also that I modified the Arrow functions by normal function statements, as there is no reason to use Arrow functions in that case. :)
In case I wanted when Handle pointed to this pointed to the props that Todo gets, like a bind in a class
– krolgon
Just use
props
, sincehandleAdd
is within the scope of the componentTodo
. Did you test it? Did you make a mistake? It seems to me it’s all right. I edited the answer to add a functional example. :)– Luiz Felipe
Thank you for your help and clarification :D
– krolgon