简体   繁体   English

如何在 props 中添加 JSX?

[英]How to add JSX inside props?

I have a component which has props value.我有一个具有props价值的组件。 This component is global and I don't want to change its source code.这个组件是全局的,我不想更改它的源代码。 I want to add pre tag inside the value prop to have a proper indentation between title and value .我想在 value prop 中添加pre标签,以便在titlevalue之间有一个适当的缩进。

<component
   title = {<strong>Name</strong>}
   value = {<pre>  {name === undefined ? myName : myNames}</pre>}
/>

Issue: I get NaN for value prop.问题:我得到NaN作为价值支柱。
How do I fix it?我如何解决它?
Also, is there a way to add a gap/padding between title and value ?另外,有没有办法在titlevalue之间添加间隙/填充? Please note that I do not wish to modify the source file of Component .请注意,我不想修改Component的源文件。

Whenever I face a situation like this, my first approach is to make a helper function to render the smaller parts and pass them as props while invoking that function simultaneously.每当我遇到这样的情况时,我的第一个方法是制作一个助手 function 来渲染较小的部分并将它们作为道具传递,同时调用 function。

For instance, for your case:-例如,对于您的情况:-

//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>
);

Codesandbox Link - https://codesandbox.io/s/eloquent-resonance-h4m49 Codesandbox 链接 - https://codesandbox.io/s/eloquent-resonance-h4m49

You can pass prop Components in that following Example what I made for live view you can check here SandBox您可以在下面的示例中传递道具组件我为实时视图制作的内容您可以在此处查看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'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM