How can I apply a style to a Bootstrap React element?

独自空忆成欢 提交于 2019-12-04 06:14:51

问题


The following is a line rendered inside a ReactJS Component for my application and saved as nav.jsx.

<span style="font-family: 'Open Sans', sans-serif;">&nbsp;Home</span>

Exception:

Uncaught Error: The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX. This DOM node was rendered by `Nav`.
    at invariant (react.js:18354)
    at assertValidProps (react.js:6435)
    at ReactDOMComponent.mountComponent (react.js:6678)
    at Object.mountComponent (react.js:12978)
    at ReactDOMComponent.mountChildren (react.js:11692)
    at ReactDOMComponent._createContentMarkup (react.js:6815)
    at ReactDOMComponent.mountComponent (react.js:6703)
    at Object.mountComponent (react.js:12978)
    at ReactDOMComponent.mountChildren (react.js:11692)
    at ReactDOMComponent._createContentMarkup (react.js:6815)

Why is this happening and how can I apply the font?


回答1:


The error states how to fix this:

Uncaught Error: The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX. This DOM node was rendered by Nav.

The style prop for elements expects an object that has keys and values corresponding to CSS properties and their values:

<span style={{fontFamily: "'Open Sans', 'sans-serif'"}}>&nbsp;Home</span>

Remember that property keys cannot contain - and that React camelCases CSS property names, so font-family becomes fontFamily.


As a side note: I would prefer an object declared outside the JSX, so that isn't inline and it's more organized (in my opinion). Another way would be just to use a CSS stylesheet instead of styles in JavaScript.



来源:https://stackoverflow.com/questions/42862670/how-can-i-apply-a-style-to-a-bootstrap-react-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!