簡體   English   中英

無法在React中從父級調用客戶端方法嗎?

[英]Can't call client methods from the parent in React?

我有一個基本的React App,看起來像這樣:

App = createClass({
    update(text){
        this.setState({params: make_params(text)})
    }
    componentWillMount() {
        this.updatePeriodic = _.throttle(this.update, 500)
    }
    render() {
        return <div>
            <SearchField cb={this.updatePeridic}/>
            <ListOfThings searchParams={this.state.params}/>
        </div>;
    }
};

哪個很棒。 我現在正嘗試添加一個重置按鈕:

App = createClass({
    update(text){
        this.setState({params: make_params(text)})
    }
    componentWillMount() {
        this.updatePeriodic = _.throttle(this.update, 500)
    }
    render() {
        search = <SearchField cb={this.updatePeridic}/>
        const reset = () => {
            search.reset()
            this.update("")
        }
        return <div>
            {search}
            <button onClick={reset} />
            <ListOfThings searchParams={this.state.params} />
        </div>;
    }
};

嘗試調用search.reset時遇到錯誤,但是該函數不存在。 我不太確定該怎么辦–我知道讓父母稱他們的孩子為setState有點奇怪,但是我沒有看到其他方法可以做到這一點。 我不想這樣做:

<SearchField value={this.state.text} cb={this.setState({text: ""})}/>

因為,A)每次有人在該字段中鍵入將導致重新提交整個APP,B)當原始文本成為App狀態的一部分時,沒有明顯的方法來限制對子ListOfThings的params更新。 有什么想法嗎?

您不能從父級調用子級方法。
你可以做什么:

  • 將參數置於父狀態,
  • 將其作為道具傳遞給孩子,
  • 使孩子響應reset參數。

像這樣:

update(text, shouldResetChild){
  this.setState({
    params: make_params(text), 
    shouldResetChild: shouldResetChild        // store action to reset child
  })
}

在您的渲染器中:

search = <SearchField 
            cb={this.updatePeridic}
            shouldReset = {this.state.shouldResetChild} />    // pass to child
const reset = () => {
  this.update("", true)
}

在孩子的某個地方(哪種生命周期方法取決於reset()作用)。

if (this.props.shouldReset) {
  this.reset()
}

PS:在父級內的任何其他setState()調用中(在您的示例中都沒有),您應包括{ shouldResetChild : false }以將參數重置為狀態,以確保重置僅發生一次/僅在重置按鈕時發生被點擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM