如何在状态下存储React组件并传递回调函数

时间:2018-12-30 09:48:47

标签: reactjs

我有一个问题,我试图将一个组件存储到我的状态中,并且还传递一个回调函数作为其道具,以便可以在CustomComponent内部调用它。 这是我所做的:

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


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

但是当我尝试在CustomComponent(this.props.testCallBack())中调用该函数时,它告诉我这不是一个函数。

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

我知道有一些用于标签的库,但是我很好奇我如何在这里做。

谢谢

2 个答案:

答案 0 :(得分:2)

您不会在状态中存储JSX,这是一种非常糟糕的做法,也是一种无效的做法。

您可以执行以下操作:

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

render方法内,您可以使用有关存储在state中的选项卡的这些数据来呈现自定义组件。

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

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

答案 1 :(得分:1)

您不应该在状态下存储react组件,状态仅用于数据:

例如:

state= {
tabs: [
{id: 1, content: "hello world",
id: 1, content: "hello world 2"
}]
}

render()中,您可以使用该数据将其转换为react组件:

render() {
const tabComponent = this.state.tabs.map((tab)=> {
<CustomComponent tabContent={tab.content} id ={tab.id} testCallback={this.callbackHandler} />
}
return (
{tabComponent}
)

希望对您有帮助!