【问题标题】:How to store react component in state and pass a callback function如何将反应组件存储在状态并传递回调函数
【发布时间】:2018-12-30 09:48:46
【问题描述】:

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

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


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

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

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

我知道有一些标签库,但我只是想知道我怎么能在这里做到这一点。

谢谢

【问题讨论】:

    标签: reactjs


    【解决方案1】:

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

    你可以这样做:

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

    【讨论】:

    • 谢谢,我最终在父组件中创建了自定义组件,然后将其作为 props.children 传递给我的选项卡组。
    【解决方案2】:

    你不应该将 react 组件存储在 state 中,state 只用于数据:

    例如:

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

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

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

    希望对你有帮助!

    【讨论】:

    • 谢谢,真的很有帮助
    猜你喜欢
    • 2021-02-18
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2018-08-20
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多