如何触发一个组件的更改。从另一个组件

时间:2018-08-06 10:55:29

标签: reactjs

我的react应用程序具有一个名为ListOfTenants的组件,该组件基本上是一个表格,每行上都有一个单选按钮。而且每次选择一行时,我都希望在顶部栏导航中,有一个组件表示“您正在处理X租户”。

所以ActiveTenant组件是这样的:

import React, { Component } from "react";
import authAction from "../../redux/auth/actions";

class ActiveTenant extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        You aaare using tenant:
        {this.state.activetenant}
      </div>
    );
  }
}

export default ActiveTenant;

listtenants组件是这样的:

import React, { Component } from "react";
import { Table, Radio } from "antd";
import { adalApiFetch } from "../../adalConfig";

class ListTenants extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }

  fetchData = () => {
    adalApiFetch(fetch, "/Tenant", {})
      .then(response => response.json())
      .then(responseJson => {
        if (!this.isCancelled) {
          const results = responseJson.map(row => ({
            key: row.ClientId,
            ClientId: row.ClientId,
            ClientSecret: row.ClientSecret,
            Id: row.Id,
            SiteCollectionTestUrl: row.SiteCollectionTestUrl,
            TenantDomainUrl: row.TenantDomainUrl
          }));
          this.setState({ data: results });
        }
      })
      .catch(error => {
        console.error(error);
      });
  };

  componentDidMount() {
    this.fetchData();
  }

  render() {
    const columns = [
      {
        title: "Client Id",
        dataIndex: "ClientId",
        key: "ClientId"
      },
      {
        title: "Site Collection TestUrl",
        dataIndex: "SiteCollectionTestUrl",
        key: "SiteCollectionTestUrl"
      },
      {
        title: "Tenant DomainUrl",
        dataIndex: "TenantDomainUrl",
        key: "TenantDomainUrl"
      }
    ];

    // rowSelection object indicates the need for row selection
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(selectedRows[0].key);
      },
      getCheckboxProps: record => ({
        type: Radio
      })
    };

    return (
      <Table
        rowSelection={rowSelection}
        columns={columns}
        dataSource={this.state.data}
      />
    );
  }
}

export default ListTenants;

还有App.js(主要组件)

import React, { Component } from "react";
import { connect } from "react-redux";
import { Layout } from "antd";
import { Debounce } from "react-throttle";
import WindowResizeListener from "react-window-size-listener";
import { ThemeProvider } from "styled-components";
import authAction from "../../redux/auth/actions";
import appActions from "../../redux/app/actions";
import Sidebar from "../Sidebar/Sidebar";
import Topbar from "../Topbar/Topbar";
import AppRouter from "./AppRouter";
import { siteConfig } from "../../settings";
import themes from "../../settings/themes";
import { themeConfig } from "../../settings";
import AppHolder from "./commonStyle";
import "./global.css";

const { Content, Footer } = Layout;
const { logout } = authAction;
const { toggleAll } = appActions;
export class App extends Component {
  render() {
    const { url } = this.props.match;
    const { height } = this.props;
    return (
      <ThemeProvider theme={themes[themeConfig.theme]}>
        <AppHolder>
          <Layout style={{ height: "100vh" }}>
            <Debounce time="1000" handler="onResize">
              <WindowResizeListener
                onResize={windowSize =>
                  this.props.toggleAll(
                    windowSize.windowWidth,
                    windowSize.windowHeight
                  )
                }
              />
            </Debounce>
            <Topbar url={url} />
            <Layout style={{ flexDirection: "row", overflowX: "hidden" }}>
              <Sidebar url={url} />
              <Layout
                className="isoContentMainLayout"
                style={{
                  height: height
                }}
              >
                <Content
                  className="isomorphicContent"
                  style={{
                    padding: "70px 0 0",
                    flexShrink: "0",
                    background: "#f1f3f6",
                    position: "relative"
                  }}
                >
                  <AppRouter url={url} />
                </Content>
                <Footer
                  style={{
                    background: "#ffffff",
                    textAlign: "center",
                    borderTop: "1px solid #ededed"
                  }}
                >
                  {siteConfig.footerText}
                </Footer>
              </Layout>
            </Layout>
          </Layout>
        </AppHolder>
      </ThemeProvider>
    );
  }
}

export default connect(
  state => ({
    auth: state.Auth,
    height: state.App.toJS().height
  }),
  { logout, toggleAll }
)(App);

如何在OnChange事件上触发ActiveTenant组件上的更改?

更新

索引(租户)

一个用于注册(表单)的标签,另一个标签是列表。

import React, { Component } from '../../../../../Library/Caches/typescript/2.9/node_modules/@types/react';
import { Row, Col, Tabs } from 'antd';
import PageHeader from '../../components/utility/pageHeader';
import Box from '../../components/utility/box';
import LayoutWrapper from '../../components/utility/layoutWrapper';
import ContentHolder from '../../components/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../components/utility/intlMessages';
import RegisterTenantForm2 from './registertenantform2';
import ListTenants from './listtenants';

export default class extends Component {
  render(){
    const { rowStyle, colStyle, gutter } = basicStyle;
    const TabPane = Tabs.TabPane;
    return (
      <div>
        <LayoutWrapper>
        <PageHeader>{<IntlMessages id="pageTitles.TenantAdministration" />}</PageHeader>
              <Tabs defaultActiveKey="1">
                <TabPane tab="Tenant Registration" key="1">
                          <Row style={rowStyle} gutter={gutter} justify="start">
                    <Col md={24} sm={24} xs={24} style={colStyle}>
                      <Box
                        title={<IntlMessages id="tabTitle.TenantRegistration" />}
                        subtitle={<IntlMessages id="pagesmalldescription.TenantRegistration" />}
                      >
                        <ContentHolder>
                            <RegisterTenantForm2 />
                        </ContentHolder>
                      </Box>
                    </Col>
                  </Row>
                </TabPane>
                <TabPane tab="Tenant List" key="2">
                  <ListTenants/>
                </TabPane>
              </Tabs>



      </LayoutWrapper>
      </div>
    );
  }
}

和approuter.js

import React, { Component } from "react";
import { Route } from "react-router-dom";
import asyncComponent from "../../helpers/AsyncFunc";

const routes = [
  {
    path: "",
    component: asyncComponent(() => import("../dashboard"))
  },
  {
    path: "TenantAdministration",
    component: asyncComponent(() => import("../RegisterTenant/index"))
  },
  {
    path: "SiteCollections",
    component: asyncComponent(() => import("../SiteCollections/index"))
  },
  {
    path: "PageTemplates",
    component: asyncComponent(() => import("../PageTemplates/index"))
  }
];

class AppRouter extends Component {
  render() {
    const { url, style } = this.props;
    return (
      <div style={style}>
        {routes.map(singleRoute => {
          const { path, exact, ...otherProps } = singleRoute;
          return (
            <Route
              exact={exact === false ? false : true}
              key={singleRoute.path}
              path={`${url}/${singleRoute.path}`}
              {...otherProps}
            />
          );
        })}
      </div>
    );
  }
}

export default AppRouter;

更新2 顶栏组件

import React, { Component } from "react";
import { connect } from "react-redux";import { Layout } from "antd";
import appActions from "../../redux/app/actions";
import TopbarUser from "./topbarUser";
import TopbarWrapper from "./topbar.style";
import themes from "../../settings/themes";
import { themeConfig } from "../../settings";
import ActiveTenant from "./activetenant";

const { Header } = Layout;
const { toggleCollapsed } = appActions;
const customizedTheme = themes[themeConfig.theme];

class Topbar extends Component {
  render() {
    const { toggleCollapsed } = this.props;
    const collapsed = this.props.collapsed && !this.props.openDrawer;
    const styling = {
      background: customizedTheme.backgroundColor,
      position: "fixed",
      width: "100%",
      height: 70
    };
    return (
      <TopbarWrapper>
        <Header
          style={styling}
          className={
            collapsed ? "isomorphicTopbar collapsed" : "isomorphicTopbar"
          }
        >
          <div className="isoLeft">
            <button
              className={
                collapsed ? "triggerBtn menuCollapsed" : "triggerBtn menuOpen"
              }
              style={{ color: customizedTheme.textColor }}
              onClick={toggleCollapsed}
            />
          </div>

          <ul className="isoRight">
            <li>
              <ActiveTenant />
            </li>
            <li
              onClick={() => this.setState({ selectedItem: "user" })}
              className="isoUser"
            >
              <TopbarUser />
            </li>
          </ul>
        </Header>
      </TopbarWrapper>
    );
  }
}

export default connect(
  state => ({
    ...state.App.toJS()
  }),
  { toggleCollapsed }
)(Topbar);

2 个答案:

答案 0 :(得分:1)

为了您的理解,我正在写这个基本示例。 activeTenant和click事件出现在Main组件中,并作为props传递给子组件。

活动租户

class ActiveTenants extends React.Component{
 constructor(props) {
    super(props)
  }

    render(){

     return(
      <h1>{this.props.activetenant}</h1>
     )

    }

}

列表租户:

class ListTenants extends React.Component{

constructor(props) {
     super(props)
}

listTenant(tenants){
    return tenants.map(t=>{
        return (
         <li data-name={t.name} id={t.id}  onClick={(e)=>{this.props.tenatClick(e)}}>{t.name}</li>
        )
    });

}

render(){

 return(
    <ul>
        {this.listTenant([
            {name:"Tenant one",id:1},
            {name:"Tenant two",id:2},
            {name:"Tenant three",id:3}
        ])}

    </ul>
  )
 }
}

主要组件:

class Main extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
        activetenant :"Default tenant"
    }
  }

 changeTenant(e){
    let ele=e.target;
        this.setState({
          activetenant:ele.getAttribute('data-name')
        });
 }

  render() {
    return (
      <div>
        <header>
            <ActiveTenants activetenant={this.state.activetenant} />
        </header>
                <div>
                        <ListTenants tenatClick={this.changeTenant.bind(this)} />               
                </div>
      </div>
    )
  }
}

ReactDOM.render(<Main />, document.querySelector("#app"));

在子组件中单击列表时,它将把changeTenant函数称为主组件,因为我们将函数与主组件绑定在一起。请找到上面示例的有效提琴:copy initialization

注意:您可以使用Redux轻松完成此操作。但是您需要花费一些时间来配置所有内容。

答案 1 :(得分:0)

如果您使用的是React 16,则可以使用新的Context API

  

在典型的React应用程序中,数据是自上而下传递的(对于   儿童)通过道具,但这对于某些类型的   许多人需要的道具(例如语言环境偏好设置,UI主题)   应用程序中的组件。上下文提供了一种共享方式   无需显式传递组件之间类似这些值   穿过树的每一层的道具。