【发布时间】:2021-12-15 05:10:39
【问题描述】:
在 state 中定义但在 state 下面未定义的 props
您好,我的代码有一个小问题。我想从 Child 调用 Parent 函数,但错误提示无法读取属性 的未定义。然后我将其更改为仅记录 this.props 但同样的错误。令人困惑的部分是它是在我评估的状态下定义的 this.props.inputValue 到 inputValue 我可以在那里使用它并且它可以工作,但是在函数消息中是 按下按钮调用它是未定义的。
孩子
class Search extends React.Component {
state = {
loading: true,
inputValue : this.props.inputValue
}
message(){
console.log(this.props)
// this.props.sendMessage("HI")
}
render() {
return (
<div className="row mb-3">
<div className="col-auto mb-3">
<label className="col-form-label text-center">Suche:</label>
</div>
<div className="col-md-3 mb-3">
<input id="Input" className="form-control" type="text"
value={this.state.inputValue}
onChange={event => this.updateInputValue(event)}/>
</div>
<div className="col-md-auto mb-3">
<button id="add" onClick={this.message} className="form-control btn btn-success" >➕</button>
</div>
</div>
)
}
updateInputValue(event) {
this.setState({
inputValue : event.target.value
})
}
}
export default Search;
家长
class App extends Component {
state ={
title: "Benutzerdatensuche",
inputValue: "Suche",
value: "0"
}
render(){
return (
<div className = "App" >
<Header title={this.state.title} />
<Search inputValue={this.state.inputValue} sendMessage={this.message.bind(this)}/>
<InfoBox />
{this.state.value}
</div>
)}
message(text){
console.log(text)
}
}
我真的不明白为什么它不起作用
【问题讨论】:
-
查看您的“父”组件,您似乎已经意识到在将类方法作为道具传递时需要绑定它们。为什么不对“CHILD”组件中的类方法做同样的事情?那就是你的问题。
标签: reactjs