[英]In React can properties of grandparents be accessed by a grandchild without the parent passing it down?
[英]Error on passing down function with argument to grandchild in React
我有以下代碼:我的主要組件是這樣的:
class Layout extends React.Component {
constructor(){
super()
this.state={
searchValue: ''
}
}
getSearchValue(searchValue){
this.setState({searchValue})
}
...
return
<Filter
getSearchValue={this.getSearchValue.bind(this)}
/>
...
}
然后我有個孩子,叫做Filter:
class Filter extends React.Component {
...
return
<SearchBar
getSearchValue={this.props.getSearchValue}
/>
...
}
最后是搜索組件本身:
class SearchBar extends React.Component {
handleEvent(e){
this.props.getSearchValue(e.target.value)
}
...
return
<input onChange={this.handleEvent.bind(this)}/>
}
現在,我很確定我有這樣的東西,但后來我搞砸了,並試圖回來,但現在我收到一條錯誤信息:
未捕獲的TypeError:this.props.getSearchValue不是函數
我的任何綁定都是錯的嗎? 我試了好幾次。
如果我放置一個console.log('Hi')並從Layout中的getSearchValue中刪除this.setState(),並且我沒有將SearchBar中的變量傳遞給this.props.getSearchValue,我將消息傳遞給控制台。 所以函數有效,但只是沒有參數。 為什么?
以下聲明中的編碼是正確的,除了額外的):
<Filter
getSearchValue={this.getSearchValue.bind(this))}
/>
否則,代碼的其他區域可能存在問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.