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

IT技术 reactjs
2021-05-18 22:20:26

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

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


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

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

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

我知道有一些用于选项卡的库,但我只是想知道我如何在这里做到这一点。

谢谢

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']} />
      )
    })
  )
}

您不应该将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 }</>);
  }

希望能帮助到你!!