Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何将react组件存储在状态并传递回调函数_Reactjs - Fatal编程技术网

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

Reactjs 如何将react组件存储在状态并传递回调函数,reactjs,Reactjs,我有一个问题,我试图将一个组件存储到我的状态中,并传递一个回调函数作为它的道具,以便可以在CustomComponent内部调用它。 以下是我所做的: state = { tabs: [ { tabID: '1', component: <CustomComponent testCallback={this.callbackHandler} />} ] } callbackHandler = () => { .... } 状态={

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

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


callbackHandler = () => {
    ....
}
状态={
选项卡:[
{tabID:'1',组件:}
]
}
callbackHandler=()=>{
....
}
但是当我尝试调用CustomComponent内部的函数(this.props.testCallBack())时,它告诉我这不是一个函数

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

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


谢谢

您不应该将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}
)
render(){
const tabComponent=this.state.tabs.map((tab)=>{
}
返回(
{tabComponent}
)

希望它有帮助!!

您不想在该州存储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']} />
      )
    })
  )
}
render(){
const{tabs}=this.state;
返回(
tabs.length>0&&tabs.map((制表符)=>{
返回(
)
})
)
}

谢谢,我最终在父组件中创建了自定义组件,然后将其作为props.children传递给我的选项卡组。谢谢,这真的很有帮助