繁体   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