简体   繁体   English

子组件内的父操作反应

[英]Parent action inside child component react

I am having two components, App and a panel.我有两个组件,应用程序和面板。 On button clcik, I add panel to the screen and all the actions corresponding actions inside of the panel is handled in the Panel component ( Actions are expand, collapse and close).在按钮 clcik 上,我将面板添加到屏幕,面板内的所有操作对应操作都在面板组件中处理(操作是展开、折叠和关闭)。 Can I execute onClose method inside of the Panel component instead in App component.我可以在 Panel 组件内而不是在 App 组件中执行 onClose 方法吗? I am having a check of if cardBody is present in the parent component.我正在检查 cardBody 是否存在于父组件中。 For removing that card im setting its body to null inside App component.为了移除该卡,我在 App 组件中将其主体设置为 null。 How can I do the same in Panel component.如何在 Panel 组件中执行相同操作。

https://codesandbox.io/s/basic-demo-card-6ywop7?file=/src/Panel.jsx:0-1022 https://codesandbox.io/s/basic-demo-card-6ywop7?file=/src/Panel.jsx:0-1022

import React, { useState } from "react";
import ReactDOM from "react-dom";
import Panel from "./Panel";
import "./styles.css";

function App() {
  const [card, setCard] = useState({
    cardId: "",
    cardBody: null
  });

  const handleClick = (cardId, cardBody) => {
    setCard({ cardId, cardBody });
  };

  const { cardId, cardBody } = card;

  return (
    <>
      <div className="main">
        <button onClick={() => handleClick("Panel 1", <h1>h1</h1>)}>
          Add Panel 1
        </button>
        <button onClick={() => handleClick("Panel 2", <div>div</div>)}>
          Add Panel 2
        </button>
      </div>
      {cardBody && (
        <div className="cards-container">
          <Panel
            key={cardId}
            cardId={cardId}
            cardBody={cardBody}
            onClose={() =>
              setCard({
                cardId: "",
                cardBody: null
              })
            }
          />
        </div>
      )}
    </>
  );
}

import React, { useState, useCallback } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faSquareMinus,
  faRectangleXmark
} from "@fortawesome/free-solid-svg-icons";

function Panel(props) {
  const [isMinimized, setIsMinimized] = useState(false);
  const { cardId, cardBody, onClose } = props;

  const onMaximize = useCallback(() => {
    setIsMinimized(!isMinimized);
  }, [isMinimized]);

  return (
    <>
      <div className={isMinimized ? "card-min" : "card"}>
        <div className="card-actions">
          <span onClick={onMaximize}>{cardId}</span>
          {!isMinimized && (
            <FontAwesomeIcon
              icon={faSquareMinus}
              onClick={() => {
                setIsMinimized(true);
              }}
            />
          )}
          <FontAwesomeIcon icon={faRectangleXmark} onClick={onClose} />
        </div>
        <div className="card-body">{cardBody}</div>
      </div>
    </>
  );
}

export default Panel;

One workaround is to control the show/hide by display: 'none'/'block' inside the Panel component.一种解决方法是在Panel组件中通过display: 'none'/'block'控制show/hide

Panel component面板组件

import React, { useImperativeHandle, useState, useCallback } from 
"react";

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faSquareMinus,
  faRectangleXmark
} from "@fortawesome/free-solid-svg-icons";

function Panel(props) {
  const [isMinimized, setIsMinimized] = useState(false);
  const { cardId, cardBody, setCard } = props;

  const onMaximize = useCallback(() => {
    setIsMinimized(!isMinimized);
  }, [isMinimized]);

  return (
    <>
      <div
        style={{ display: cardBody ? "block" : "none" }}
        className={isMinimized ? "card-min" : "card"}
      >
        <div className="card-actions">
          <span onClick={onMaximize}>{cardId}</span>
          {!isMinimized && (
            <FontAwesomeIcon
              icon={faSquareMinus}
              onClick={() => {
                setIsMinimized(true);
              }}
            />
          )}
          <FontAwesomeIcon
            icon={faRectangleXmark}
            onClick={() =>
              setCard({
                cardId: "",
                cardBody: null
              })
            }
          />
        </div>
        <div className="card-body">{cardBody}</div>
      </div>
    </>
  );
}

export default Panel;

App.js应用程序.js

import React, { useState, useRef } from "react";
import ReactDOM from "react-dom";
import Panel from "./Panel";
import "./styles.css";

function App() {
  const [card, setCard] = useState({
    cardId: "",
    cardBody: null
  });

  const handleClick = (cardId, cardBody) => {
    setCard({ cardId, cardBody });
  };

  const { cardId, cardBody } = card;

  return (
    <>
      <div className="main">
        <button onClick={() => handleClick("Panel 1", <h1>h1</h1>)}>
          Add Panel 1
        </button>
        <button onClick={() => handleClick("Panel 2", <div>div</div>)}>
          Add Panel 2
        </button>
      </div>
      <div className="cards-container">
        <Panel
          key={cardId}
          cardId={cardId}
          cardBody={cardBody}
          setCard={setCard}
        />
      </div>
    </>
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

This is working example 这是工作示例

Also, you can completely conditionally show and hide the inner content of the panel but you need some modifications in the style by moving the "card-min" and "card" class to an inner div instead of the root element on the component.此外,您可以完全有条件地showhide panel的内部内容,但您需要通过将"card-min""card" class 移动到内部 div 而不是组件上的根元素来对样式进行一些修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Navigation - 在子组件中监听父动作 - React Navigation - Listen parent action in child component 使用反应在父级中执行子组件操作 - Execute child component action in the parent using react react-Native:在父组件内部访问子组件函数 - react-Native: Access child component function inside parent component 反应:在子组件函数中未定义父组件的“ this.state” - React: 'this.state' of parent component is undefined inside a child component function 在 React 的父组件中触发动作时获取子状态 - Get child state when the action is triggered in parent component in React 在父组件中反应子组件 - React child Component in parent Component 在 React 中将数据传递给父级时,根据子级操作重新渲染子组件 - Re render child component depending on child action while passing data to parent in React Redux:在子组件调度Redux操作时通知父React组件 - Redux: Notify parent React component when the child component dispatches a Redux action TypeError:无法读取 React 组件内未定义的属性“名称”,用作另一个父组件内的子组件 - TypeError: Cannot read property 'name' of undefined inside React component used as child inside another parent component 如何销毁父组件中的子组件 - How to destroy a child component inside a parent component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM