如何在变量中存储非自封闭标记并在render()方法中调用它?

时间:2018-03-16 16:12:11

标签: javascript reactjs jsx

我有以下内容:

<Col xs={6} md={2}>
    <Card someProp={myProp} />
</Col>

<Col></Col>是一个网格组件。我想根据变量的值以不同的方式设置道具。如果它是一个自封闭标记,我只需将它存储在一个变量中,并在render方法中调用它:

let someVar = <Col xs={6} md={2} />

if(someCondition) {
    someVar = <Col xs={12} md={6} />
}

{someVar} // Called like so...

但它不是一个自封的标签,这样做会导致错误:

let someVar = <Col xs={6} md={2}>

if(someCondition) {
    someVar = <Col xs={12} md={6}>
}

{someVar}
    <Card someProp={myProp} />
</Col>

如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

您可以构建一个组件,传递someVar并将其传播给实际的孩子(警告:let SomeVar = ({children}) => <Col xs={6} md={2}>{children}</Col> if(someCondition) { SomeVar = ({children}) => <Col xs={12} md={6}>{children}</Col> } <SomeVar> <Card someProp={myProp} /> </SomeVar> 应该大写):

let SomeVar = ({children}) => {
    if(someCondition) {
        return <Col xs={6} md={2}>{children}</Col>
    }
    else {
        return <Col xs={12} md={6}>{children}</Col>
    }
}

<SomeVar>
    <Card someProp={myProp} />
</SomeVar>

或者:

public class ARInvoiceEntryExtension : PXGraphExtension<ARInvoiceEntry>
{
    public PXAction<ARInvoice> exportReport;
    [PXUIField(DisplayName = "Export Report")]
    [PXButton]
    public virtual IEnumerable ExportReport(PXAdapter adapter)
    {
        //Report Paramenters
        Dictionary<String, String> parameters = new Dictionary<String, String>();
        parameters["ARInvoice.DocType"] = Base.Document.Current.DocType;
        parameters["ARInvoice.RefNbr"] = Base.Document.Current.RefNbr;

        //Report Processing
        PX.Reports.Controls.Report _report = PXReportTools.LoadReport("AR641000", null);
        PXReportTools.InitReportParameters(_report, parameters,
                SettingsProvider.Instance.Default);
        ReportNode reportNode = ReportProcessor.ProcessReport(_report);

        //Generation PDF
        byte[] data = PX.Reports.Mail.Message.GenerateReport(reportNode,
        ReportProcessor.FilterPdf).First();

        PX.SM.FileInfo file = new PX.SM.FileInfo(reportNode.ExportFileName + ".pdf", null, data);

        UploadFileMaintenance graph = new UploadFileMaintenance();
        graph.SaveFile(file);
        PXNoteAttribute.AttachFile(Base.Document.Cache, Base.Document.Current, file);

        return adapter.Get();
    }
}

答案 1 :(得分:1)

为什么不使用if...else逻辑仅定义props,而不是像这样定义整个组件:

let colProps = someCondition ? { xs: 6, md: 2 } : { xs: 12, md: 6 };

<Col {...colProps}>
    <Card someProp={myProp} />
</Col>

希望这有帮助。

答案 2 :(得分:0)

<Col xs={someCondition ? 6 : 12} md={someCondition ? 2 : 6}>
    <Card someProp={myProp} />
</Col>