简体   繁体   English

React扩展组件渲染函数调用

[英]React Extended Component Render function call

let say,i have a component, which is in render function of extended component. 比方说,我有一个组件,它是扩展组件的渲染功能。

as only one render function will call , if i remove the function from "Panel" it will work on "ExtendedComponent", is their any other way. 因为只有一个渲染函数会调用,如果我从“面板”中删除它,它将在“ExtendedComponent”上工作,是他们的任何其他方式。 so only by function i can render "SomeComponent" from "ExtendedComponent" 所以只能通过函数我可以从“ExtendedComponent”渲染“SomeComponent”

 class ExtendedComponent extends React.Component { constructor(props) { super(props); this. state = { showComponent: false, }; } render() { console.log(this.state); const {showComponent} = this.state; return showComponent ? ( <SomeComponent content="Message sent" />) : null; } toggleComponent = () => { console.log("came here"); this.setState(({showComponent}) => ({showComponent: !showComponent})); }; } 

 class Panel extends ExtendedComponent { componentDidMount() { this.toggleToast(); } render() { return ( <div> <h1>Hey!!!!!</h1> </div> ); } } 

There are two ways to have the super component rendering instead of the subcomponent: 有两种方法可以使超级组件呈现而不是子组件:

  • Removing the render method from the subcomponent 从子组件中删除render方法
  • Explicitly returning super.render(); 显式返回super.render();

The second one is suitable in your case since it would work dynamically. 第二个适用于您的情况,因为它将动态工作。

class Panel extends ExtendedComponent {
  constructor(props) {
    super(props);
    this.state = { foo: true };
  }

  componentDidMount() {
    this.toggleToast();
  }

  render() {
    if (this.state.foo) {
      return super.render();
    }
    return (
      <div>
        <h1>Hey!!!!!</h1>
      </div>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM