如何在状态中存储反应组件并传递回调函数

如何在状态中存储反应组件并传递回调函数

本文介绍了如何在状态中存储反应组件并传递回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我试图将一个组件存储到我的状态中,并将一个回调函数作为它的 props 传递,以便它可以在 CustomComponent 中被调用.这是我所做的:

I have a problem where I'm trying to store a component into my state and also pass a callback function as its props so that it can be called inside CustomComponent.Here's what I did:

state = {
    tabs: [
        { tabID: '1', component: <CustomComponent testCallback={this.callbackHandler} />}
    ]
}


callbackHandler = () => {
    ....
}

但是当我尝试调用 CustomComponent 内部的函数( this.props.testCallBack() )时,它告诉我这不是一个函数.

But when I try to call the function inside CustomComponent ( this.props.testCallBack() ), it tells me this is not a function.

像这样在 state 中存储组件可以吗?基本上,我想构建我自己的选项卡组组件,我可以在不同的选项卡中显示不同的组件.回调函数用于让父组件知道何时应该添加新选项卡.

Is it OK to store a component inside state like this?Basically, I want to build my own tab group component where I can display different components in different tabs. The callback function is used to let the parent component know when it should add a new tab.

我知道有一些用于选项卡的库,但我只是想知道如何在此处实现.

I know there are some libraries for tabs, but I'm just curious how I can do it here.

谢谢

推荐答案

您不想在状态中存储 JSX.相反,为它存储模型数据,并循环遍历您的数据以打印您的元素!

You don't want to store JSX in the state.Instead, store the model data for it, and loop through your data to print your elements!

你可以这样做:

state = {
    tabs: [
        { tabID: '1', callbackFunctionName: callbackFunction1 }
    ]
}

在您的 render 方法中,您可以使用这些关于您存储在 state 中的选项卡的数据来渲染您的自定义组件.

And inside your render method, you can use these data about the tabs you have stored in your state to render your custom component.

render(){
  const { tabs } = this.state;

  return (
    tabs.length > 0 && tabs.map((tab) => {
      return (
        <CustomComponent testCallback={this.tab['callbackFunctionName']} />
      )
    })
  )
}

这篇关于如何在状态中存储反应组件并传递回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:27