请查看下面的代码段。我试图呈现一个闪烁的文本,当它不出现时,留一个空白。但是,React似乎只是一起删除了所有元素。如何在React中正确渲染空白空间?试图进行各种跨度的搜索和测试,但仍无所获。谢谢。

class Blinker extends React.Component {
    constructor(props) {
    super();
    this.state = {
      appear: true
    }
    this.blinker = this.blinker.bind(this);
  }

  blinker()  {
    this.setState({appear: !this.state.appear });
  }

  componentDidMount() {
    setInterval(this.blinker, 1000)
  }

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

  render() {
    const name = "testing";
    const underScore = "_";
    const com = "com";
    return (
      <div>
        <div id="test"> { name } </div>
        <div id="test">
          { (this.state.appear) ? underScore : ' '}
        </div>
        <div id="test"> { com } </div>
      </div>
    );
  }
}



ReactDOM.render(<Blinker />, app);
#test {
  display: inline-block;
}
<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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div>

最佳答案

您可以使用<span>&nbsp;&nbsp;</span>:

class Blinker extends React.Component {
    constructor(props) {
    super();
    this.state = {
      appear: true
    }
    this.blinker = this.blinker.bind(this);
  }

  blinker()  {
    this.setState({appear: !this.state.appear });
  }

  componentDidMount() {
    setInterval(this.blinker, 1000)
  }

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

  render() {
    const name = "testing";
    const underScore = "_";
    const com = "com";
    return (
      <div>
        <div id="test"> { name } </div>
        <div id="test">
          { (this.state.appear) ? underScore : <span>&nbsp;&nbsp;</span>}
        </div>
        <div id="test"> { com } </div>
      </div>
    );
  }
}



ReactDOM.render(<Blinker />, document.getElementById('app'));
#test {
  display: inline-block;
}
<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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div>

关于javascript - 在React中渲染空白空间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46656476/

10-16 15:51