【问题标题】:blinking text with React using state and setTimeOutReact 使用 state 和 setTimeOut 闪烁文本
【发布时间】:2017-08-11 04:55:38
【问题描述】:

我正在尝试使用 react 显示闪烁的文本:

class BlinkLable extends React.Component {
    constructor(props) {
    super(props);
    this.state = {showlabel: true,
                 label: this.props.label
                 };
    this.myFunction = this.myFunction.bind(this);

}

myFunction()  
{
    var sLb = ! (this.state.showlabel);
    this.setState({showlabel: sLb});
}

componentDidMount() {
    setTimeout(this.myFunction, 3000)
 }

render() {
    return (
      <div>
        {(this.state.showlabel)?this.state.label:''}
      </div>
     );
    }
}

ReactDOM.render(
   <BlinkLable label='MY MESSAGE'/>,
      document.getElementById('labelId')
);

但是,在它显示 MY MESSAGE 之后,此消息就会消失并且永远不会回来。可能是什么问题?

【问题讨论】:

    标签: reactjs settimeout jsx


    【解决方案1】:

    你需要使用setInterval()方法。

    componentDidMount() {
        setInterval(this.myFunction, 3000)
     }
    

    更多信息:'setInterval' vs 'setTimeout'

    【讨论】:

      【解决方案2】:

      将此函数修改为:

      myFunction()  
      {
          this.setState((prevState) => {
            return { 
              showlabel: !prevState.showLabel
            }
          });
      }
      

      【讨论】:

        【解决方案3】:

        class BlinkLable extends React.Component {
          constructor(props) {
            super(props);
            this.state = {showlabel: true,
                         label: this.props.label
                         };
            this.myFunction = this.myFunction.bind(this);
          }
          myFunction(){
            var sLb = ! (this.state.showlabel);
            this.setState({showlabel: sLb});
          }
          render(){
            return (
              <div>
                {(this.state.showlabel)?this.state.label:''}
              </div>
             );
          }
          componentDidUpdate() {
             setTimeout(this.myFunction, 2000)
          }
          componentDidMount(){
            setTimeout(this.myFunction, 2000)
          }
        }
        
        
        ReactDOM.render(
           <BlinkLable label='MY MESSAGE'/>,
              document.getElementById('labelId')
        );
        <div id="labelId"></div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

        你需要知道react的组件life cycle

        componentDidMount() 仅在组件被安装时调用。

        componentDidMount() 在组件被调用后立即调用 安装。需要 DOM 节点的初始化应该放在这里。

        因此,如果您想继续闪烁,请添加 componentDidUpdate()

        【讨论】:

          猜你喜欢
          • 2022-10-17
          • 2023-03-18
          • 1970-01-01
          • 2017-03-08
          • 2018-01-30
          • 1970-01-01
          • 2016-05-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多