【问题标题】:How to pass prop values defined in Child comp to its Parent comp-reactJs如何将 Child comp 中定义的 prop 值传递给其 Parent comp-reactJs
【发布时间】:2017-11-03 16:35:20
【问题描述】:

我知道这个问题已经在堆栈溢出中得到解决,但对我来说,我有更具体的要求。我想在子组件中定义道具的值,并能够将其值传递给其祖父组件。 我要定义值的子组件:

const Child = React.createClass(

   onselect(status) {
    let testProp = {refs: this.refs.statetext, status:status}
  }
    render() {
         return (
                <Mycomp ref="statetext"/>
        );
});

家长比较:

const Parent = React.createClass(
//can I access the refs.statetext here???
        render() {
             return (
                    <Child/>
            );
    });

祖父母比较:

const GrandParent = React.createClass(
    //here I'd like to access the testProp defined in the Child comp
           closeMenu() {
              //should have the testProp value here to do some action in this function.
           }
            render() {
                 return (
                        <Parent onScroll={this.closeMenu.bind(this)}/>
                );
        });

这可能吗?

【问题讨论】:

  • 它没有回答你的问题,但 ref 通常是一种不好的反应实践,你只是不思考反应。为什么不在您的祖父母中启动它或使用 storeManager ?
  • @Nevosis 使用ref 在某些情况下很好,与“在 React 中思考”没有任何关系。如果你想要一个不受控制的输入,你必须使用ref,例如。

标签: reactjs


【解决方案1】:

看来您只需要一个将向上传递到Grandfather 组件的事件。在 React 中,props 向下流动,events 向上流动。因此,下面的代码通过Parent 将onSelect 事件冒泡到Grandfather:

const Child = React.createClass(

   onselect(status) {
    let testProp = {refs: this.refs.statetext, status:status}
    this.props.onSelect(testProp);
  }
    render() {
         return (
                <Mycomp ref="statetext"/>
        );
});

然后:

const Parent = React.createClass(
//here I'd like to access the testProp defined in the Child comp
        render() {
             return (
                    <Child onSelect={this.props.onSelect} />
            );
    });

然后:

const GrandParent = React.createClass(
    //here I'd like to access the testProp defined in the Child comp
           closeMenu() {
              //should have the testProp value here to do some action in this function.
           }


           onSelect(testProp) {
              // here it is :)
              // you can now save it in state, so it will be available when the menu is closed.
              console.log(testProp);
           }

            render() {
                 return (
                        <Parent onScroll={this.closeMenu.bind(this)} onSelect={this.onSelect.bind(this)} />
                );
        });

【讨论】:

    【解决方案2】:

    声明/初始化 Grandfather 组件中的变量,并通过 props 将其传递给 Child。
    这就是展示/容器组件的重点。如果您的 Child 组件依赖于 Grandfather 组件,那么您的状态应该存在于此。

    【讨论】:

    • 我认为问题是如何使数据反向流动。顺便说一句,我不是反对者。
    • 但这是问题的正确答案。 React 是单向的,你不能通过组件向上传递道具。您可以使用 refs 作为解决此问题的方法,但这不是 react 方法。
    • 好的,那么在这种情况下,我可以访问祖父母内部的 Child Comp 中定义的 ref 吗?
    • 查看@DavinTryon 的回答,因为我相信它更适合您的需求。
    猜你喜欢
    • 2011-01-13
    • 2018-03-12
    • 1970-01-01
    • 2021-12-27
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多