简体   繁体   中英

How to render a string in reactjs

I have an object with keys and values. I'd like to render a certain keys value in my react JSX markup like this:

const VALUES = {
  "key1": "value 1",
  "key2": "value 2",
}

const MyComponent = ({name}) => (
  VALUES[name] || ""  
)

but this does not work. While it is legal to render strings directly in JSX like this: <span>A string</span> the code above fails with an error saying "inst.render is not a function" in _renderValidatedComponentWithoutOwnerOrContext .

It works if the values look like this:

const VALUES = {
  "key1": <span>value 1</span>,
  "key2": <span>value 2</span>,
}

I'm going to go out on a limb and assume this is because const MyComponent has a signature of () => string and not () => ReactElement ; This error is occuring because React is attempting to call .render() on the return value of your function and it can't find it, so it breaks.

Indeed, it would appear that render() on a component can only return ReactElement | null | false ReactElement | null | false ReactElement | null | false . Given that in a stateless component, the function itself is a render() function, it would logically follow that your component must have the signature () => ReactElement | null | false () => ReactElement | null | false () => ReactElement | null | false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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