I am trying to render a simple input field, in which when the value is changed, a callback from the parent component will be called. My code is given below:
class Parent extends React.Component {
myMethod() {
alert("Test");
}
render() {
return (
<Child cb={this.myMethod} />
);
}
}
class Child extends React.Component {
render() {
return (
<input type="text" placeholder="enter text" onChange="{this.props.cb}" />
);
}
}
Child.propTypes = {
cb: React.PropTypes.func
}
ReactDOM.render(
<Parent />,
document.getElementById("container")
);
My HTML code is:
<div id="container">
</div>
The error I am getting is:
Warning: Failed prop type: Child: prop type `cb` is invalid; it must be a function, usually from React.PropTypes.
in Child (created by Parent)
in Parent
Warning: Failed form propType: Invalid prop `onChange` of type `string` supplied to `input`, expected `function`. Check the render method of `Child`.
I am new to React, and cannot really understand how else I should pass the callback to the Child component. Can someone help please?
Your onChange prop shouldn't be string:
class Child extends React.Component {
render() {
return (
<input type="text" placeholder="enter text" onChange={this.props.cb} />
);
}
}
删除 onChange
值周围的引号 :
<input type="text" placeholder="enter text" onChange={this.props.cb} />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.