如何将Child comp中定义的prop值传递给它的Parent comp-reactJs

时间:2017-11-03 16:35:20

标签: reactjs

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

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/>
            );
    });

GrandParent Comp:

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)}/>
                );
        });

这可能吗?

2 个答案:

答案 0 :(得分:4)

您似乎只需要一个将流向Grandfather组件的事件。在React中,props向下流动,events向上流动。因此,下面的代码通过onSelectGrandfather事件发送到Parent

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)} />
                );
        });

答案 1 :(得分:-1)

声明/初始化Grandfather组件中的变量,并通过道具将其传递给Child
这是演示/容器组件的重点。如果您的Child组件依赖于Grandfather组件,那就是您的州应居住的地方。