【问题标题】:How to add JSX inside props?如何在 props 中添加 JSX?
【发布时间】:2021-11-24 08:10:45
【问题描述】:
我有一个具有props 值的组件。这个组件是全局的,我不想更改它的源代码。
我想在 value 属性中添加 pre 标签,以便在 title 和 value 之间有适当的缩进。
<component
title = {<strong>Name</strong>}
value = {<pre> {name === undefined ? myName : myNames}</pre>}
/>
问题:我得到 NaN 作为价值道具。
我如何解决它?
另外,有没有办法在title 和value 之间添加间隙/填充?请注意,我不想修改Component的源文件。
【问题讨论】:
标签:
javascript
reactjs
jsx
【解决方案1】:
您可以在下面的示例中传递 prop Components 我为实时取景制作的内容,您可以在此处查看 SandBox
import React, { useState } from 'react';
import { render } from 'react-dom';
const Success = () => {
return <pre>Your state isn't undefined</pre>
}
const Undefined = () => {
return <pre>Your state isn't undefined</pre>
}
const ReturnProp = ({propJSX}) => {
return propJSX
}
const App = () => {
const [name, setName] = useState(undefined)
return <ReturnProp propJSX={name===undefined? <Undefined />: <Success />}/>
}
render(<App />, document.querySelector('#app'));
【解决方案2】:
每当我遇到这样的情况时,我的第一个方法是创建一个辅助函数来渲染较小的部分并将它们作为道具传递,同时调用该函数。
例如,对于您的情况:-
//helper function to render title
const renderTitle = () => {
return <strong>Name</strong>;
};
//helper function to render value, you can also add styles to them via inline styles or using class or id.
const renderValue = () => {
return (
<pre style={{ marginLeft: 15 }}>
{name === undefined ? "myName" : "myNames"}
</pre>
);
};
return (
<div style={{ display: "flex" }}>
<CustomComponent title={renderTitle()} value={renderValue()} />
// invoking the helper functions to render the title and value
</div>
);
代码沙盒链接 - https://codesandbox.io/s/eloquent-resonance-h4m49