在反应和未定义中将数据从子级传递到父级不是函数

时间:2018-07-20 11:53:12

标签: reactjs react-native

我需要将数组从子组件传递到父组件。 我在父组件中所做的是:

handlerfordata=(data)=>{
        console.log('Inside handlerfordata data is');
        console.log(data);
    }
Inide return in render .Note Child is name of my child component

return(
          <View>

           <Child  handlerfordata={this.handlerfordata()}/>
           </View>
      );

现在在我的子组件中,我已经做了类似的事情

 handleSave = () => {
           //finalvalue is an array that is computed and i can see it in my console and handlesave is triggeed at onclick in child component inside return 
           console.log('finalValue is ',finalValue);
            this.props.handlerfordata(finalValue);
       }

另一件事是,子组件在屏幕上呈现,但是我只想访问子组件中的数据,而不是呈现它。

5 个答案:

答案 0 :(得分:1)

传递引用handlerfordata,而不传递this.handlerfordata()

应该是

<Child  handlerfordata={this.handlerfordata}/>
                       ^^^^^^^^^^^^^^^^^^^^^^

答案 1 :(得分:1)

通过添加此代码

<Child  handlerfordata={this.handlerfordata()}/>

您没有传递引用,而是在调用此函数。

将其更改为

<Child  handlerfordata={this.handlerfordata}/>

只会通过引用。

然后您可以使用props从子组件中调用它。

答案 2 :(得分:1)

您必须绑定处理程序:

<Child handlerfordata={this.handlerfordata.bind(this)} />

答案 3 :(得分:0)

ReactJS以一种数据流方式(自上而下)着称,这意味着从父级到子级的任何数据流向或传递都应在一个方向上。

如果您需要以另一种方式传递数据,则可以尝试应用redux状态管理。

在您尝试的代码中,它只是将方法从父级传递到子级。

答案 4 :(得分:0)

要调用该方法,您需要将子元素中的引用传递为

<Child  handlerfordata={this.handlerfordata}/>

如果不渲染子组件,则无法访问子数据。我更喜欢使用redux,以便所有状态都在单个存储中。