代码之家  ›  专栏  ›  技术社区  ›  Finesse

如何将元素移动到另一个保持其状态和DOM的父元素?

  •  1
  • Finesse  · 技术社区  · 7 年前

    我有以下React应用程序:

    class Item extends React.PureComponent {
      state = {
        id: Math.random()
      };
    
      divRef = React.createRef();
    
      render() {
        return <div ref={this.divRef}>
          My id is {this.state.id}
        </div>;
      }
    
      componentDidMount() {
        // This is a DOM manipulation which React doesn't control. I use it to see whether React reuses the DOM element.
        const colors = ['red', 'blue', 'green', 'navy', 'brown', 'violet'];
        const color = colors[Math.floor(Math.random() * colors.length)];
        this.divRef.current.style.color = color;
      }
    }
    
    class App extends React.Component {
      state = {
        itemPosition: 'top'
      };
    
      render() {
        return <React.Fragment >
          <button onClick={() => this.setState({itemPosition: 'top'})}>Move to top</button>
          <button onClick={() => this.setState({itemPosition: 'bottom'})}>Move to bottom</button>
          <div className="container">
            {this.state.itemPosition === 'top' ? <Item key="1"/> : null}
          </div>
          <div className="container">
            {this.state.itemPosition === 'bottom' ? <Item key="1"/> : null}
          </div>
        </React.Fragment>;
      }
    }
    
    ReactDOM.render(<App/>, document.querySelector('#app'));
    .container {
      border: solid 1px;
      padding: 10px;
      margin: 10px;
    }
    <script src="https://cdn.jsdelivr.net/npm/react@16.4.1/umd/react.development.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/react-dom@16.4.1/umd/react-dom.development.js"></script>
    
    <div id="app"></div>

    在本例中 App 组件呈现 Item 二合一组件 div s、 在 项目 组件每次安装以检测重新安装时都会随机出现。

    如你所见 项目 元素每次移动到另一个父级时都会重新装入 迪夫 . 有没有一种方法可以将元素移动到另一个父元素而不必卸载和装载它来保持元素状态和相应的DOM树?

    P、 我知道我可以通过移动 项目

    0 回复  |  直到 7 年前