[英]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: 我想像这样在我的React JSX标记中呈现某些键值:
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
. 虽然它是合法的呈现字符串直接在JSX这样的: <span>A string</span>
上面的代码失败,错误说“inst.render是不是一个函数”在_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
; 我打算走出去,这是因为const MyComponent
的签名是() => string
而不是() => 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. 发生此错误是因为React试图在函数的返回值上调用.render()
,但找不到它,因此它中断了。
Indeed, it would appear that render()
on a component can only return ReactElement | null | false
实际上, 似乎组件上的render()
只能返回ReactElement | null | false
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
鉴于在无状态组件中,该函数本身是render()
函数,因此从逻辑() => ReactElement | null | false
,您的组件必须具有签名() => ReactElement | null | false
() => ReactElement | null | false
() => ReactElement | null | false
. () => ReactElement | null | false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.