Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

reactjs - How to store react component in state and pass a callback function

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...