- 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.props
in the child component. - Below there are three components outlined in the code editor. The
MyApp
component is the parent that will render theGetInput
andRenderInput
child 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
GetInput
component to the render method inMyApp
sstate
. Also create a prop calledhandleChange
and pass the input handlerhandleChange
to it. Next, addRenderInput
to the render method inMyApp
, then create a prop calledinput
and pass theinputValue
fromstate
to it. Once you are finished you will be able to type in theinput
field in theGetInput
component, which then calls the handler method in its parent via props. This updates the input in thestate
of 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)