首页 > 解决方案 > 如何根据 child.in React with hooks 的响应有条件地显示面包屑名称?

问题描述

我目前正在使用 React Hooks 开发一个项目。

父组件是一个导航器

  1. 子组件是此导航器中的面包屑显示。
  2. 子组件获取并显示包含数据的视图。

如何使用 2. 子组件中的响应数据在 1. 子组件中设置名称?

我的代码(本示例省略了大部分不必要的代码):

航海家

const { Header, Content } = Layout;
const Navigation = (props: any) => (
    <>
        <Layout>
            <Layout>
                <Header>
                    <Breadcrumbs
                        style={{ flexGrow: 2, paddingLeft: 20 }}
                        name='Name of User'
                    />

                </Header>
                <Content style={{ margin: '24px 16px 0', overflow: 'hidden' }}>
                    <div className="content">
                        <Switch>
                            <Route exact path="/" component={MyPatients} />
                            <Route exact path="/Skjema" component={MySchemas} />
                            <Route
                                exact
                                path="/Pasient"
                                component={() => 
                                    <PatientInfo
                                        patientID={props.history.location.state}
                                    />
                                }
                            />
export default withRouter(Navigation);

面包屑

import React from 'react';
import Breadcrumb from 'antd/lib/breadcrumb';
import { HomeOutlined, UserOutlined } from '@ant-design/icons';

const Breadcrumbs = (props: any) => {

    return (

        <>
            <div className="Breadcrumbcontainer" style={props.style}>
                <Breadcrumb>
                    <Breadcrumb.Item href="/">
                        <HomeOutlined />
                        <span style={{ color: 'black' }}>Hjem</span>
                    </Breadcrumb.Item>
                    <Breadcrumb.Item href="Pasient">
                        <UserOutlined />
                        <span style={{ color: 'black' }}>
                            {props.name}
                        </span>
                    </Breadcrumb.Item>
                    <Breadcrumb.Item>
                        <span>Skjema 1 - 17.04.20</span>
                    </Breadcrumb.Item>
                </Breadcrumb>
            </div>
        </>
    );
};

export default Breadcrumbs;

第三个文件包含对 api 的提取并且工作正常,有问题的数据当前存储为 response.name 我怎样才能将此信息提升到 Navigator?

标签: javascriptreactjsfrontendreact-hooks

解决方案


如果我正确理解了您的问题,那么有一个父组件有两个子组件,并且您想触发从一个子组件到另一个子组件的更改。

您可以在父组件中维护状态,在 child1 中传递状态,在 child2 中传递 setState 函数。

// Parent Component
const [name, setName] = useState('');

<>
  <child1 name={name}/>
  <child2 setName={setName}/>
</>


推荐阅读