如何在React / Redux / Typescript通知消息中从自身上卸下,取消渲染或删除组件

reactjs React.js

L路易

2020-03-12

我知道这个问题已经被问过几次了,但是在大多数情况下,解决方法是在父级中解决这个问题,因为责任流只是在下降。但是,有时您需要通过一种方法杀死组件。我知道我无法修改其道具,如果我开始将布尔值添加为状态,那么对于一个简单的组件而言,它将会变得非常混乱。我正在尝试实现以下目标:一个小的错误框组件,使用“ x”将其关闭。通过其道具接收到错误将显示该错误,但是我想一种从其自己的代码中关闭该错误的方法。

class ErrorBoxComponent extends React.Component {

  dismiss() {
    // What should I put here ?
  }

  render() {
    if (!this.props.error) {
      return null;
    }

    return (
      <div data-alert className="alert-box error-box">
        {this.props.error}
        <a href="#" className="close" onClick={this.dismiss.bind(this)}>&times;</a>
      </div>
    );
  }
}


export default ErrorBoxComponent;

我会在父组件中这样使用它:

<ErrorBox error={this.state.error}/>

在本节中 我应该放在这里什么?,我已经尝试过:

ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode); Which throws a nice error in the console :

Warning: unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. Instead, have the parent component update its state and rerender in order to remove this component.

Should I copy the incoming props in the ErrorBox state, and manipulate it only internally ?

第1085篇《如何在React / Redux / Typescript通知消息中从自身上卸下,取消渲染或删除组件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
6的不行 2020.03.12

我去过这个帖子大约十次了,我只想在这里留下两分钱。您可以有条件地卸载它。

if (renderMyComponent) {
  <MyComponent props={...} />
}

您要做的就是将其从DOM中删除以便卸载。

只要renderMyComponent = true,组件将呈现。如果设置renderMyComponent = false,它将从DOM卸载。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android