提问者:小点点

如何将子组件中定义的属性值传递给其父组件


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

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

这有可能吗??


共2个答案

匿名用户

似乎您只需要一个事件,它将流向老爷子组件。在React中,props向下流动,事件向上流动。所以,下面的代码,通过onSelect事件冒泡到祖父

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

匿名用户

声明/初始化爷爷组件中的变量,并通过道具将其传递给孩子
这就是表示/容器组件的要点。如果你的组件依赖于祖父组件,那就是你的状态应该存在的地方。