如何在三元运算中呼叫功能元件 [英] How to call a function component as part of a ternary operation
问题描述
我有以下三元代码片段,有条件地渲染了一个React Fragment,如下所示:
I have the following ternary code snippet that conditionally renders a React Fragment as shown below:
return (
<Formik
{({ values, errors, isSubmitting, isValid, setFieldValue }) => (
{
jobName === 'ABC' ? (
<React.Fragment>
<FieldArray name="myGroups">
{({ push, remove}) => (
<React.Fragment>
<Grid item xs={12}>
<Typography variant="h6">
My Heading
</Typography>
</Grid>
)}
</FieldArray>
</React.Fragment>
) : null
}
)}
</Formik>
);
我的问题是,作为 else
或):null
部分的一部分,我实际上想执行以下代码操作,但仍然保留 null
,但不确定如何实现,即:
My question is, as part of the else
or ) : null
section, I would actually like to perform the following code operation(s) but still keep the null
but unsure how to achieve this, i.e.:
setFieldValue(fieldArrayKey, []);
null;
我想作为)的一部分:null
,我是否可以实际调用以某种方式封装以下代码的功能组件:
I guess as part of the ) : null
, can I actually call a function component that encapsulates somehow the following code:
setFieldValue(fieldArrayKey, []);
null;
,然后调用):< SetField/>
推荐答案
您可以做的是创建一个函数并从中返回null,然后在返回之前对该函数进行任何操作
What you could do is create a function and return null from it and do any stuff in that function before returning
const jobName = "ABCc";
function otherFn() { // ADD A FUNCTION
setFieldValue("fieldArrayKey", []);
return <SetField />;
}
return <div>{jobName === "ABC" ? <A /> : null}</div>; // FROM
return <div>{jobName === "ABC" ? <A /> : otherFn()}</div>; // TO
这篇关于如何在三元运算中呼叫功能元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!