Reactjs 如何在react中将纯组件替换为shouldComponentUpdate
我有以下反应组件Reactjs 如何在react中将纯组件替换为shouldComponentUpdate,reactjs,react-native,Reactjs,React Native,我有以下反应组件 import React, { Component } from 'react'; import Backdrop from 'components/ui/backdrop/backdrop.component'; class BaseModal extends Component { shouldComponentUpdate(nextProps: INextProps) { return nextProps.show !== this.props.show
import React, { Component } from 'react';
import Backdrop from 'components/ui/backdrop/backdrop.component';
class BaseModal extends Component {
shouldComponentUpdate(nextProps: INextProps) {
return nextProps.show !== this.props.show || nextProps.children !== this.props.children;
}
render() {
const { show, modalClosed } = this.props;
return (
<div>
<Backdrop show={show} onClick={modalClosed} />
<div
className='modalClass'
style={{
transform: show ? 'translateY(0)' : 'translateY(-100vh)',
opacity: this.props.show ? '1' : '0',
}}>
>{this.props.children}
</div>
</div>
);
}
}
interface IProps {
show: boolean;
modalClosed: boolean;
children: any;
}
interface INextProps {
show: boolean;
children: any;
}
export default BaseModal;
import React,{Component}来自'React';
从“components/ui/background/background.component”导入背景;
类BaseModel扩展组件{
shouldComponentUpdate(下一步:下一步){
返回nextrops.show!==this.props.show | | nextrops.children!==this.props.children;
}
render(){
const{show,modalClosed}=this.props;
返回(
>{this.props.children}
);
}
}
接口IProps{
显示:布尔;
modalClosed:布尔型;
儿童:任何;
}
接口取消触发{
显示:布尔;
儿童:任何;
}
导出默认BaseModel;
我想在这里使用纯组件。这是否意味着我可以从此组件中删除shouldComponentUpdate生命周期方法?如果是这样,我应该怎么做?您可以在此处安全地删除shouldComponentUpdate生命周期方法。通常不应使用此生命周期。如果您所做的只是通过引用比较道具,那么您可以使用PureComponent安全地替换它的功能(阅读更多关于何时应该使用其中一种) 您还可以删除INextProps接口,因为它实际上并不需要(您也应该在shouldComponentUpdate中使用相同的接口IProps) 这里是组件的改进版本,它使用PureComponent而不是组件
import React from 'react';
import Backdrop from 'components/ui/backdrop/backdrop.component';
class BaseModal extends React.PureComponent {
render() {
const { show, modalClosed, children } = this.props;
return (
<div>
<Backdrop show={show} onClick={modalClosed} />
<div
className='modalClass'
style={{
transform: show ? 'translateY(0)' : 'translateY(-100vh)',
opacity: show ? '1' : '0',
}}>
>
{children}
</div>
</div>
);
}
}
interface IProps {
show: boolean;
// by the way you are using it, it seems like modalClosed is a function not a bool
modalClosed: () => void;
children: any;
}
export default BaseModal;
从“React”导入React;
从“components/ui/background/background.component”导入背景;
类BaseModel扩展了React.PureComponent{
render(){
const{show,modalClosed,children}=this.props;
返回(
>
{儿童}
);
}
}
接口IProps{
显示:布尔;
//通过使用它的方式,modalClosed似乎是一个函数,而不是bool
modalClosed:()=>无效;
儿童:任何;
}
导出默认BaseModel;