React 学习笔记

React v16


unmountComponentAtNode

ReactDOM.unmountComponentAtNode 方法只能销毁 ReactDOM.render的组件节点,不能销毁React组件里render生成的节点;

先定义一个子组件

//子组件
class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: props.value
        };
    }
    render() {
        return (
            <div> {this.state.value} </div>
        );
    }
}

父组件里,错误使用案例

//父组件
class ParentBox extends React.Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
      //此处使用unmountComponentAtNode是无效的;
      const childDiv = ReactDOM.findDOMNode(this.refs.childDiv);
      ReactDOM.unmountComponentAtNode(childDiv);
    }
    componentWillUnmount() {
    }
    render() {
        return (
            <Child value={'Loading...'} ref={'childDiv'} />
        );
    }
}

父组件里,正确使用

//父组件
class ParentBox extends React.Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
      //先定义一个Child子组件,此处设置ref会报错
      ReactDOM.render(<Child id={'childDiv2'} value={'123'}/>, document.getElementById('childBox'));
      //删除子组件,此处使用unmountComponentAtNode有效  
      ReactDOM.unmountComponentAtNode(document.getElementById('childBox'));
    }
    componentWillUnmount() {
    }
    render() {
        return (
            <div>
                 {/*<Child value={'Loading...'} ref={'childDiv'} />*/}

                 <div id={'childBox'} />  
            </div>  
        );
    }
}

参考:https://github.com/itbilu/react-demos/blob/master/demo5/unmountComponentAtNode.html


Donate
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2022 Peng Xiang
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信