Created
November 20, 2018 18:14
-
-
Save matheusrod92/b01b2d48c2a5729e3186fe210f54c573 to your computer and use it in GitHub Desktop.
Como atualizar estado de um componente pai em react
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
const Filho = (props) => ( | |
<div> | |
<b>Eu sou um componente stateless</b> | |
<span> mas eu controlo o state do meu pai!</span> | |
<input | |
type="text" | |
value={props.valorDoPapaizineo} | |
onChange={(event) => props.setStateDoPapaizineo(event.target.value)} | |
/> | |
</div> | |
); | |
Filho.propTypes = { | |
valorDoPapaizineo: PropTypes.string.isRequired, | |
setStateDoPapaizineo: PropTypes.func.isRequired, | |
}; | |
class Pai extends React.Component { | |
state = { | |
papaizineo: '', //string vazia porque não podemos passar null para input | |
}; | |
issoAlteraOMeuEstado = (value) => { | |
this.setState({ papaizineo: value }); //atualizo o meu state | |
}; | |
render() { | |
return ( | |
<div> | |
<h1>State do pai:</h1> | |
<span>{this.state.papaizineo}</span> | |
<Filho | |
valorDoPapaizineo={this.state.papaizineo} //passo valor do estado pro filho | |
setStateDoPapaizineo={this.issoAlteraOMeuEstado} //passo a função para o filho sem chamar ela | |
/> | |
</div> | |
); | |
} | |
} | |
export default Pai; |
Parabéns! Ajudou bastante.
Show @alaodev, fiz isso pra um amigo há um bom tempo. Se precisar de dicas e/ou exemplos de front pode me mandar uma mensagem nas redes:
https://twitter.com/matheusrod92
https://www.linkedin.com/in/matheusrod92/
Show meu brother! Obrigado... Estava quebrando a cabeça aqui passando a função com arrow kkkk
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Parabéns! Ajudou bastante.