如何阻止React TypeScript中组件递归显示(Form嵌套场景)
解决方法
核心思路是给Form组件加一个可选属性,用来控制按钮的显示状态——默认显示按钮,当在MyWindow里嵌套Form时,关闭这个开关即可。
步骤1:扩展Form组件的Props接口
给Form的Props添加一个可选的showButton属性,默认值设为true:
interface Props { showButton?: boolean; }
步骤2:根据属性控制按钮渲染
在Form的render方法里,通过this.props.showButton判断是否渲染按钮:
public render() { const { showButton = true } = this.props; return ( <div> {showButton && ( <Button onClick={() => this.setState({ showWindow: true })} > Show Window </Button> )} {this.state.showWindow && ( <MyWindow/> )} </div> ); }
步骤3:在MyWindow中关闭按钮显示
在MyWindow里使用Form时,传入showButton={false},嵌套的Form就不会显示按钮了:
export const MyWindow: React.FC<Props> = props => { return ( <Window> <Form showButton={false}/> </Window> ); };
修改后的完整代码
父组件
interface Props { showButton?: boolean; } interface State { showWindow: boolean; } export class Form extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { showWindow: false, }; } public render() { const { showButton = true } = this.props; return ( <div> {showButton && ( <Button onClick={() => this.setState({ showWindow: true })} > Show Window </Button> )} {this.state.showWindow && ( <MyWindow/> )} </div> ); } }
子组件
interface Props {} export const MyWindow: React.FC<Props> = props => { return ( <Window> <Form showButton={false}/> </Window> ); };
内容的提问来源于stack exchange,提问作者Barry
相关产品推荐
相关产品推荐

