[英]How to export react jsx component in an object?
For clean code & folder structure, I'm moving some data (in this case, modal data) to a separate file.对于干净的代码和文件夹结构,我将一些数据(在本例中为模态数据)移动到单独的文件中。 However, I'm not able to put a component inside an object value.
但是,我无法将组件放入 object 值中。 Here's what I want to do:
这是我想要做的:
export function invalidId(id) {
return {
info: {
title: "Invalid ID!",
message: (
<>
The
<code className="inline-code">{id}</code>
is invalid. Please make sure blah blah blah...
</>
),
},
// I need help with this part
buttons: {
<>
<Button label="Retry" />
<Button label="More Info" >
</>
}
}
}
import { invalidId } form "modaldata";
setModalInfo(invalidId(id).info);
setModalButtons(invalidId(id).buttons);
I used return
here because id
is dynamic.我在这里使用
return
因为id
是动态的。 The main problem is buttons
part.主要问题是
buttons
部分。 What is the correct way to put JSX inside an object?将 JSX 放入 object 的正确方法是什么?
Remember that a JSX expression results in an object value (it gets converted into a call to React.createObject(/*...*/)
or whatever else is set up as the JSX function).请记住,JSX 表达式会生成 object 值(它会转换为对
React.createObject(/*...*/)
的调用或任何其他设置为 JSX 函数的内容)。 Like any other value, if you want to put that value inside an object, you either need to:与任何其他值一样,如果您想将该值放入 object 中,您需要:
Just use the fragment directly (not within another object);直接使用片段(不在另一个对象内); or
或者
Use a property name (or names);使用属性名称(或名称); or
或者
Use an array使用数组
(Or make buttons
a function that returns the fragment, as abhi patil shows .) (或将
buttons
设为返回片段的 function,如abhi patil 所示。)
Here's #1 (note no {}
):这是#1(注意没有
{}
):
buttons: <>
retry: <Button label="Retry" />
moreInfo: <Button label="More Info" >
</>
Here's #2, assuming you want separate property names for the two buttons:这是#2,假设您想要两个按钮的单独属性名称:
buttons: {
retry: <Button label="Retry" />,
moreInfo: <Button label="More Info" >,
}
Here's #3, an array (rather than plain object) containing the two buttons:这是#3,一个包含两个按钮的数组(而不是普通对象):
buttons: [
<Button label="Retry" />,
<Button label="More Info" >,
]
You need to return the jsx template in a object field and call it like a function.您需要在 object 字段中返回 jsx 模板,并像 function 一样调用它。
export function invalidId(id) {
return {
info: {
title: "Invalid ID!",
message: ()=> (
<>
The
<code className="inline-code">{id}</code>
is invalid. Please make sure blah blah blah...
</>
),
},
// I need help with this part
buttons:()=> (
<>
<Button label="Retry" />
<Button label="More Info" >
</>
)
}
}
setModalButtons(invalidId(id).buttons();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.