reactjs 如何阻止组件递归显示在react Typescript中

pobjuy32  于 2023-06-22  发布在  React
关注(0)|答案(2)|浏览(103)

我有一个父组件Form,它有一个按钮,当用户单击时,它将显示一个子组件MyWindow。MyWindow组件也有Form组件,因此按钮也会出现在MyWindow中。如何在MyWindow打开时阻止按钮在MyWindow中显示?我只希望按钮出现在父窗体中。

// parent component --------
interface State {
    showWindow: boolean;
}

export class Form extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props);
        this.state = {
            showWindow: false,
        };
    }

    public render() {
        return (
            <div>
                <Button
                    onClick={() => this.setState({ showWindow: true })}
                >
                    Show Window
                </Button>
                {this.state.showWindow && (
                    <MyWindow/>
                )}
            </div>
        );
    }
}

// child component --------

interface Props {}

export const MyWindow: React.FC<Props> = props => {
    return (
        <Window>
            <Form/>
        </Window>
    );
};
n9vozmp4

n9vozmp41#

你可以在你的子组件中添加一个prop,以知道它在form中:

// parent component --------
interface ParentProps {
    isInside?: boolean;
}

interface State {
    showWindow: boolean;
}

export class Form extends React.Component<ParentProps, State> {
    constructor(props: Props) {
        super(props);
        this.state = {
            showWindow: false,
        };
    }

    public render() {
        return (
            <div>
               {!isInside && (
                <Button
                    onClick={() => this.setState({ showWindow: true })}
                >
                    Show Window
                </Button>)}
                {this.state.showWindow && (
                    <MyWindow/>
                )}
            </div>
        );
    }
}

// child component --------

interface Props {}

export const MyWindow: React.FC<Props> = props => {
    return (
        <Window>
            <Form isInside />
        </Window>
    );
};
66bbxpm5

66bbxpm52#

您可以在表单组件中创建一个布尔属性,并使用它来呈现按钮组件。

// parent component --------
interface State {
    showWindow: boolean;
}

export class Form extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props);
        this.state = {
            showWindow: false,
        };
    }

    public render() {
        return (
            <div>
               {
               !!!this.props.hideButton &&
                <Button
                    onClick={() => this.setState({ showWindow: true })}
                >
                    Show Window
                </Button>
                }
                {this.state.showWindow && (
                    <MyWindow/>
                )}
            </div>
        );
    }
}

// child component --------

interface Props {}

export const MyWindow: React.FC<Props> = props => {
    return (
        <Window>
            <Form hideButton={true}/>
        </Window>
    );
};

相关问题