我正在尝试渲染一个简单的输入字段,其中当值更改时,将调用来自父组件的回调。我的代码如下:
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")
);
我的HTML代码是:
<div id="container">
</div>
我得到的错误是:
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`.
我是React的新手,并且无法理解我应该如何将回调传递给Child组件。有人可以帮忙吗?
答案 0 :(得分:1)
删除onChange
:
<input type="text" placeholder="enter text" onChange={this.props.cb} />
答案 1 :(得分:1)
你的onChange道具不应该是字符串:
class Child extends React.Component {
render() {
return (
<input type="text" placeholder="enter text" onChange={this.props.cb} />
);
}
}