- You can also pass handler functions or any method that's defined on a React component to a child component. This is how you allow child components to interact with their parent components. You pass methods to a child just like a regular prop. It's assigned a name and you have access to that method name under
this.propsin the child component. - Below there are three components outlined in the code editor. The
MyAppcomponent is the parent that will render theGetInputandRenderInputchild components.
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
inputValue: event.target.value
});
}
render() {
return (
<div>
{ /* Change code below this line */ }
{ /* Change code above this line */ }
</div>
);
}
};
class GetInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>Get Input:</h3>
<input
value={this.props.input}
onChange={this.props.handleChange}/>
</div>
);
}
};
class RenderInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>Input Render:</h3>
<p>{this.props.input}</p>
</div>
);
}
};
What they want us to do is add the
GetInputcomponent to the render method inMyAppsstate. Also create a prop calledhandleChangeand pass the input handlerhandleChangeto it. Next, addRenderInputto the render method inMyApp, then create a prop calledinputand pass theinputValuefromstateto it. Once you are finished you will be able to type in theinputfield in theGetInputcomponent, which then calls the handler method in its parent via props. This updates the input in thestateof the parent, which is passed as props to both children.Answer:
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
inputValue: event.target.value
});
}
render() {
return (
<div>
<GetInput handleChange = {this.handleChange} input = {this.state.inputValue} />
<RenderInput input = {this.state.inputValue}/>
</div>
);
}
};
Top comments (0)