You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 16:22:51