我正在尝试创建一个 React 组件,它包装输入并将更改后的输入的值传递给其父级。 我可以通过委托(delegate) onchange 函数 trought 属性来将事件传递给父组件,但我更愿意将从事件中提取的新值封装在子组件中。
这是我的组件代码:
class BigInputField extends React.Component<IBigInputField, {}>{
handleChange(event){
console.log("handleChange method called !");
debugger;
let value = event && event.target && event.target.value;
this.props.onChangeSetValue(value);
};
render(){
return (
<input type="search" value = {this.props.value} onChange= {this.handleChange} id="main_search_field" className="form-control" placeholder="Stuff to input"/>
);
}
}
问题是,当我在输入中输入某些内容时,react 会提示 this.props.onChangeSetValue(value) 不是一个函数。 当我在调试器语句中检查 this.props 时,我得到一个值为“form-control”的 className 成员、一个值为“Stuff to input”的占位符、一个值为“main_search_field”的 id ...。 看来我没有获得父级传输的 Prop ,而是获得了由我的组件渲染的子级的 Prop ! 这可能是 chrome 调试器的问题,它没有正确设置 this 值,但它并不能解释为什么我的 this.props.onChangeSetValue 似乎不存在。
在父级中, Prop 设置如下:
<BigInputField onChangeSetValue= {this.setSearchValue} value= this.state.search}/>
我已经检查了父级的渲染函数“this.setSearchValue”是正确的函数。
你如何解释这一点?
谢谢。
最佳答案
您是否将this
绑定(bind)到您的组件?当在 React 组件中使用 es6 extends 时,你应该这样做:
class BigInputField extends React.Component<IBigInputField, {}>{
constructor(props) {
super(props);
//need to bind custom functions to the component due to how extends works in es6
this.handleChange = this.handleChange.bind(this);
}
...
render () { // return here }
}
关于javascript - 包装输入时,React 属性未正确设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32681887/