className
属性将类应用于JSX元素,并将样式应用于样式表中的类。另一种选择是应用内联样式,这在ReactJS开发中非常常见。您将内联样式应用于JSX元素,类似于您在HTML中的操作方式,但有一些JSX差异。以下是HTML中内联样式的示例: <div style="color: yellow; font-size: 16px">Mellow Yellow</div>
JSX元素使用style
属性,但由于JSX的转换方式,您可以不要将值设置为string
。相反,您将其设置为等于JavaScript object
。这是一个例子: <div style={{color: "yellow", fontSize: 16}}>Mellow Yellow</div>
注意我们如何使用“fontSize”属性?这是因为React不接受样式对象中的kebab-case键。 React将在HTML中为我们应用正确的属性名称。 div
添加style
属性,为文本提供红色和字体大小为72px的颜色。请注意,您可以选择将字体大小设置为数字,省略单位“px”,或将其写为“72px”。 div
元素。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return mockedComponent.children().type() === "div"; })(), "The component should render a div
element.");'
- text: div
元素应该是red
。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return mockedComponent.children().props().style.color === "red"; })(), "The div
element should have a color of red
.");'
- text: ''
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return (mockedComponent.children().props().style.fontSize === 72 || mockedComponent.children().props().style.fontSize === "72" || mockedComponent.children().props().style.fontSize === "72px"); })(), "The div
element should have a font size of 72px
.");'
```