我有一个简单的react组件,它传递一个对象数组,其中一个值是另一个React组件,如下所示(是的,我知道这可以转换为功能组件,但这对于这个问题无关紧要):
import React, { Component } from 'react'
import GeneralPage from 'AdminApp/client/components/conference/GeneralPage'
import TopicPage from 'AdminApp/client/components/conference/TopicPage'
import NewPage from 'common/client/components/wizard/NewPage'
export default class TestWizard extends Component {
render() {
let steps=[
{name: "One", node: GeneralPage},
{name: "Two", node: TopicPage},
{name: "Three", node: TopicPage},
]
return (
<NewPage steps={steps} name='Conference'/>
)
}
}
这在另一个碰巧包含在单独的HOC中的组件中,但是HOC与这个问题无关,我正在创建从上面传入的组件 - 下面的代码中的React.createElement(step.node):
import React, { Component, PropTypes } from 'react'
import {NewWrapper} from 'common/client/components/wizard/NewWrapper'
import WizardButtons from 'common/client/components/wizard/WizardButtons'
import { bindActionCreators } from 'redux'
import CONSTANTS from 'common/client/constants'
let NewPage = NewWrapper(class extends Component {
render() {
const {steps, page, name} = this.props
let stepCount = steps.length
let stepName = steps[page - 1].name
let submit = steps[page - 1].submit
let stepPreText = `${name}`
let stepPostText = ` Wizard - ${stepName} (Step ${page} of ${stepCount})`
//TODO: select with steps - if ID and/or valid?
let title = <div><h2 style={{textAlign: 'center', color: CONSTANTS.EP_COLOR_BROWN}}>
{name && stepPreText}{stepCount > 1 && stepPostText}
</h2></div>
return (
<div>
{page}
{steps.map((step, index) =>
<div key={index}>
{page === (index + 1) ? title : null}
{/* ***HERE IS WHERE THE NODES ARE ADDED *** */}
{page === (index + 1) ? React.createElement(step.node) : null}
</div>
)}
{/* ***I NEED TO ADD THIS AS A CHILD TO THE createElement *** */}
<WizardButtons submit={submit} {...this.props}/>
</div>
)
}
})
export default NewPage
我需要做什么,似乎无法弄清楚如何将上面的<Wizard Buttons/>
元素添加为createElement的子元素。我厌倦了React.createElement(step.node, null, <WizardButtons submit={submit} {...this.props}/>)
之类的东西,并使用向导按钮元素创建变量,并将该变量作为第3个参数传递给creatElement,但似乎没有任何效果。关于如何最好地做到这一点的任何想法?
TIA!
答案 0 :(得分:2)
尝试更改
let steps=[
{name: "One", node: GeneralPage},
{name: "Two", node: TopicPage},
{name: "Three", node: TopicPage},
]
到
let steps=[
{name: "One", node: <GeneralPage />},
{name: "Two", node: <TopicPage />},
{name: "Three", node: <TopicPage />},
]
和这个
{page === (index + 1) ? React.createElement(step.node) : null}
到
{page === (index + 1) ? step.node : null}
已修改为将按钮添加到step.node
要将向导按钮添加到step.node ......您可以执行某些操作
let wizardButton = <WizardButtons submit={submit} {...this.props}/>
React.cloneElement(step.node, {wizardButton : wizardButton});
您将在step.node
中将其作为道具答案 1 :(得分:0)
好的,感谢@QoP指出我正确的方向,我终于弄明白了......
let wizardButtons = <WizardButtons submit={submit} {...this.props}/>
{page === (index + 1) ? React.createElement(step.node, {...this.props}, wizardButtons) : null
将按钮作为子项传递给每个步骤节点,步骤节点中的this.props.children显示它们。