繁体   English   中英

将样式导入到React组件中时,如何分配基于关闭状态进行更新的className?

[英]When importing styles into a React component, how do I assign a className that updates based off state?

我正在使用样式加载器将css模块化注入到我的组件({style.exampleClassName})中。

我想显示一个加载器一段设定的时间,然后显示一个图像(这些元素中至少16个以网格模式显示)。

我当前的组件如下所示:

 // Child Component /** * * Sets up props for the child (icon) * */ import React, { Component } from 'react'; import styles from './styles.css'; class Child extends React.Component { constructor(props) { super(props); this.state = { hidden : "shown", loading: "loading" }; } componentDidMount() { const self = this; const wait = this.props.wait; console.log('mounted'); setTimeout(() => { console.log('timeout working ' + wait); self.setState({ hidden: "hidden", loading: "loaded" }); }, wait); } render() { const hidden = `styles.${this.state.hidden}`; const loading = `styles.${this.state.loading}`; return ( <div> <link rel="stylesheet" type="text/css" href="./app/components/socialgrid/styles.css" /> <div className={this.state.hidden}> <p>Loading...</p> </div> <div className={this.state.loading}> <p>Child - {this.props.wait}ms</p> </div> </div> ) } }; export default Child; // Parent /** * * Individual Icon Component * */ import React, { Component } from 'react'; import cx from 'classnames'; import Img from 'components/Img'; import Child from './Child'; // import Fb from './Fb.png'; class IndIcon extends React.Component{ render() { return ( <div> <div> <Child wait={1000} /> <Child wait={5000} /> <Child wait={4000} /> </div> </div> ) } }; export default IndIcon; 
 .hidden, .loading{ display: none; } 

通常,我的样式会通过className = {styles.exampleClassName}进行自我注入,但是在这里,我遇到了由于类别基于状态而改变而无法注入类的问题(正如我上面所说的,只是尝试用不同的措词来说明) 。

我想分配的不仅仅是display:none元素,所以我确实需要这些组件上的类。

帮助将不胜感激。 谢谢!

您还差得远...您只是没有将const变量传递到JSX中。 尝试按以下方式修改渲染功能(以粗体突出显示的修正):

render() {
    const hidden = `styles.${this.state.hidden}`;
    const loading = `styles.${this.state.loading}`;

      return (
        <div>
        <link rel="stylesheet" type="text/css" href="./app/components/socialgrid/styles.css" />
          <div className={hidden}>
              <p>Loading...</p>
          </div>
          <div className={loading}>
              <p>Child - {this.props.wait}ms

</div> </div> ) }

注意:以这种方式将样式包含在组件中会污染全局CSS命名空间,如果您具有样式(如果您在应用程序的其他位置(由您自己或由其他开发人员)定义的相同名称),则可能导致问题,这可能导致无法预测的样式行为

即使我真的想在状态更改时更新这些类,我还是改走了这条路线,并且走得更好:

 import React, { Component } from 'react'; import Spinner from './Spinner'; import Icon from './Icon'; class Child extends React.Component { constructor(props){ super(props); this.state = { loading: true } } componentDidMount(){ const wait = this.props.wait; setTimeout(() => { this.setState({ loading: false }) }, wait) } render() { let content = this.state.loading ? <div><Spinner /></div> : <div><Icon /></div>; return ( <div>{content}</div> ) } }; 

这样,它将根据状态更改和settimeout加载组件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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