【问题标题】:Component is not being styled according to className组件未根据 className 设置样式
【发布时间】:2022-01-04 00:46:26
【问题描述】:

由于某种原因,设置 className 没有设置我的属性:

export default class MyComponent extends Component {
  render() {
    return(
      <div className={styles.example}>
     </div>
    )
  }
}

const styles = StyleSheet.create({
  example: {
    background: 'black',
    width: '100px',
    height: '100px'
  }
})

它只是呈现类似的东西

<div class="175">
</div>

没有样式信息(“类”175 没有 CSS 规则)

为什么不(如我所料)以 styles__example___2w27N 之类的名称结束,并在浏览器中指定 CSS 规则

.styles__example___2w27N {
    background-color: 'black';
    height: 100px;
    width: 100px;
}

如何应用我的 CSS?


如果我使用style={styles.example}(而不是className),我实际上会得到this error

style 属性需要从样式属性到值的映射,而不是字符串。

我更喜欢使用className,因为

  • 我已经指定了悬停和活动样式,style 可以使用这些样式吗?
  • 我想手动添加和覆盖一些内联样式

【问题讨论】:

  • @Vektor 我应该看什么?
  • @theonlygusti,你用的是 react-native 还是 react js web?
  • react-nativereactJS 基本相似,但它们不能共享相同的代码

标签: javascript reactjs react-native


【解决方案1】:

您应该使用&lt;View&gt; 组件而不是&lt;div&gt; 组件,因为这会将&lt;View&gt; 组件映射到您正在使用的每个特定平台的本机视图UI 组件(即:&lt;div&gt;用于 web,android.view 用于 android 等),而不是直接使用 &lt;div&gt; 元素。

这样,&lt;View&gt; 元素和其他 react-native 核心组件被设计为与 StyleSheet 一起使用。你应该将你的风格应用到所有核心组件都有的style prop,而不是className prop:

<View style={styles.example}>
</View>

在网络上查看上述内容时,您会看到源代码中使用了 &lt;div&gt;,但在其他平台上,您会看到正在使用其他原生视图 UI 类型。

【讨论】:

  • 为什么会这样?
  • 我只是不知道 react 和 react-native 是不同的东西
  • @theonlygusti 是的,他们使用类似的想法,但主要是您使用的组件/元素不同。状态等核心概念仍然相同
  • 我为什么能够首先在 react-native 中渲染&lt;div&gt;?并渲染其他开发者的 reactJS 组件?
  • @theonlygusti 我个人不知道他们允许它的具体原因,但是当您在 react-native 中使用 &lt;div&gt; 时,它仍然可以像在 reactjs 中一样工作,但是那些组件使用 html 元素构建的元素只能在 Web 上运行,而在 iOS/Android 设备上查看时将无法运行,因为它们不会像 Web 那样理解如何处理和呈现 &lt;div&gt; 元素。
【解决方案2】:

样式表指的是React Native...你是在做react-js还是react native?

假设你正在做 react-js(因为 div),那么 react-js 中没有样式表之类的东西......

export default class MyComponent extends Component {
  render() {
    return(
      <div className={styles.example}>
     </div>
    )
  }
}

const styles = {
  example: {
    background: 'black',
    width: '100px',
    height: '100px'
  }
}

我认为您是从 react-native 文档而不是 react-js 复制代码...

【讨论】:

  • 现在班​​级是[object Object]
  • 你是在做 react-native 还是 react-js?
  • 你能用style={styles.example}代替className吗?
  • 使用style= 我得到“style 道具需要从样式属性到值的映射,而不是字符串”
  • 这是 react-js 还是 react native?
猜你喜欢
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 2020-10-08
  • 2021-01-01
  • 2020-11-17
  • 2016-11-26
  • 2018-07-10
  • 2020-10-15
相关资源
最近更新 更多