假设,我有一个组件,它是扩展组件的渲染函数。
因为只有一个渲染函数会调用,如果我从"面板"中删除该函数,它将在"扩展组件"上工作,这是他们的任何其他方式。 所以只有通过函数我才能从"扩展组件"中渲染"某个组件">
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>
);
}
}
有两种方法可以让超级组件而不是子组件呈现:
- 从子组件中删除呈现方法
- 显式返回
super.render();
第二个适合您的情况,因为它可以动态工作。
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>
);
}
}