Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 = () => {
    ....
}

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

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.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.8k views
Welcome To Ask or Share your Answers For Others

1 Answer

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!

you can do this:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...