简体   繁体   English

样式标签在渲染时从 ReactJS 组件中完全消失

[英]style tag completely disappears from ReactJS component on render

Here is the code, not sure if this is an issue with React or a simple typo, but as soon as this component renders, the entire style tag disappears.这是代码,不确定这是 React 的问题还是简单的错别字,但是一旦此组件呈现,整个样式标记就会消失。 What this code does is change the transform scale every 750ms to a random size between 0 and 0.5, but as stated, it's having an issue even rendering the tag, which is strange.这段代码所做的是每 750 毫秒将变换比例更改为 0 到 0.5 之间的随机大小,但如上所述,即使渲染标签也存在问题,这很奇怪。

let styles = { 
    transform: `scale(0.5);` 
}

function changeStyle() {
    var r = -0.1 + Math.random() * (0.2 - 0) + 0;
    styles = { 
        transform: `scale(${r});` 
    };
    setTimeout(changeStyle, 750);
}

changeStyle();

export default class Runaway extends Component {

    componentDidMount() {
        console.log("Booting up Runaway button v1 by Ashe Muller.")
    }

    render() {
        return (
            <div style={{styles}}>
                <text id="shopItemGrid">RUN AWAY</text>
            </div>
        )
    }
}

The way the code is structured now, styles would never change, because changeStyle() is never getting called within the component.现在代码的结构方式, styles永远不会改变,因为changeStyle()永远不会在组件内被调用。

Try something like this:尝试这样的事情:

export default class Runaway extends Component {
  constructor() {
      super();
      this.state = {
        transform: 'scale(0.5)'
      }
  }

  handleTransformChange = () => {
    var r = -0.1 + Math.random() * (0.2 - 0) + 0;
    var newTransform = `scale(${r})`;
    this.setState({
      transform: newTransform
    });
  }

  componentDidMount() {
    console.log("Booting up Runaway button v1 by Ashe Muller.")
    this.timer = setInterval(
      () => this.handleTransformChange(),
      750
    );
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  render() {
    let styles = { 
      transform: this.state.transform
    };

    return (
      <div style={styles}>
        <text id="shopItemGrid">RUN AWAY</text>
      </div>
    );
  }
}

your let 'styles' is already an object and should be passed as such to your div style:你的 let 'styles' 已经是一个对象,应该像这样传递给你的 div 样式:

<div style={styles}>

so that the result would be :结果是:

<div style={{ transform: `scale(0.5);` }}>

In your case you're adding a level of object and finally your style looks like this:在您的情况下,您正在添加一个对象级别,最后您的样式如下所示:

style={{ styles : { transform: `scale(0.5);` }}

which is not a valid style.这不是有效的样式。

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

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