簡體   English   中英

如何從一個子組件在父組件中設置 state 並使用 react 和 typescript 在另一個子組件中訪問 state?

[英]How to set state in parent from one child component and access the state in another child component using react and typescript?

我想在單擊子組件中的按鈕時在父組件中設置 state。 我也想在其他子組件中訪問這個 state。

我想做什么? 單擊上傳按鈕(UploadButton 組件)時,我希望將 state isDialogOpen 設置為 true。 我想在 UserButton 組件中訪問 isDialogOpen state 。

下面是片段,

function Main() {
    return (
        <Wrapper>
            <React.Suspense fallback={null}>
                <Switch>
                    <Route
                        exact
                        path="/page1"
                        render={routeProps => (
                            <Layout>
                                <React.Suspense fallback={<PlaceHolder></>}>
                                    <child1 {...routeProps} />
                                </React.Suspense>
                            </Layout>
                        )}
                    />
                    <Route
                        exact
                        path="/page2"
                        render={routeProps => (
                            <Layout>
                                <Child2 {...routeProps} />
                            </Layout>
                        )}
                    />
                </Switch>
            </React>
        </Wrapper>
    )
}


function Child1() {
    return (
        <UploadButton/>
    );
}

type Props = RouteComponentProps<{ itemId: string; productId: string }>;

function UploadButton({ match }: Props) { //here i set the state isDialogOpen
    const [isDialogOpen, setDialogOpen] = React.useState(false);

    const handle_click = () => {
        setDialogOpen(!isDialogOpen);
    };

    return (
        <>
            <Button onClick={handle_click}/>

            {isDialogOpen && (
                <UploadForm/>
            )}
        </>
    );
}


function Child2() {
    return (
        <UserButton/>
    );
}

function UserButton() {
    return (
        <Icon/>
    );
}

在上面的代碼片段中,在 UploadButton 組件中設置了 isDialogOpen state。

現在我想修改上面的代碼片段,如果 isDialogOpen 為真,則隱藏 UserButton 組件中的 Icon 組件。

我想在 UserButton 組件中訪問這個 isDialogOpen state。

我試過什么?

我可以在主組件中定義一個 function 當在 UploadButton 組件中單擊 Upload 按鈕時將 isDialogOpen 設置為 true。 但這需要將 function 作為道具從主組件傳遞到上傳按鈕,同樣將 state 從主組件傳遞給 UserButton。

有沒有一些巧妙的方法可以做到這一點? 我是 typescript 的新手並做出反應。 有人可以幫我解決這個問題。 謝謝。

您應該將 state 值和 function 定義為分別將 state 更新為道具,將子組件作為道具。 您可以以我在下面提供的代碼為例

 const Child1 = (props) => { return <div>This is the counter value {props.counter}</div> } const Child2 = (props) => { return <div> <h2>Here the button to update the counter</h2> <button onClick={props.update}> Update counter state in the parent </button> </div> } class MainComponent extends React.Component { constructor(props) { super(props); this.state = { counter: 0 } } updateCounter = () => { this.setState({counter: this.state.counter + 1}); } render() { return <div> <Child1 counter={this.state.counter} /> <Child2 update={this.updateCounter} /> </div> } } ReactDOM.render(<MainComponent />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

您可以將相同的組件與上下文 API 和 React HOOKS像這樣使用

import React, { useContext, useState} from 'react';

const CounterContext = React.createContext({
    counter: 0
});

const MainComponent  = (props) => {
    const [counter, setCounter] = useState(0);
    
    const updateCounter = () => {
        setCounter(counter + 1);
    }

    return <CounterContext.Provider value={
        counter,
        update: updateCounter
    }>
        <div>
            <Child1 />
            <Child2 />
        </div>
    </CounterContext.Provider>;
}


const Child1 = (props) => {
    const counter = useContext(CounterContext);
    return <div>This is the counter value {counter.counter}</div>
}

const Child2 = (props) => {
    const counter = useContext(CounterContext);

    return <div>
        <h2>Here the button to update the counter</h2>
        <button onClick={counter.update}>
            Update counter state in the parent
        </button>
    </div>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM