2

当收到 erro.message === '2 factory code wrong' 我希望显示一个弹出窗口。逻辑相当简单,但是,我无法弄清楚如何让这个弹出窗口在某处监听布尔值,如何让它在某处监听布尔值?

这里相当简单的组件:

  import React, { useState, useEffect } from 'react';
import { ErrorMessage, useField } from "formik";
import { StyledTextInput, StyledLabel, StyledIcon, ErrorMsg } from "./Styles";

// Eye for password
import { FiEyeOff, FiEye } from "react-icons/fi";
import Popup from "reactjs-popup";

function MyComponent() { 
  const [state, setState] = useState();
  setState(true);
  return (
    <Popup model> <span> teste</span> </Popup>
  );
}

export const TextInput = ({ icon, ...props }) => {
  const [field, meta] = useField(props);
  const [showpass, setShowpass] = useState(false);
  const [showPopup, setShowPopup] = useState(false);

  useEffect(() => {
    if(meta.error){
    setShowPopup(true);
    }
  }, [meta.error])
  
  return (
    <div style={{ position: "relative" }}>
      <StyledLabel htmlFor={props.name}>{props.label}</StyledLabel>
      {props.type !== "password" && (
        <StyledTextInput
          invalid={meta.touched && meta.error}
          {...field}
          {...props}
        />
      )}
      {props.type === "password" && (
        <StyledTextInput
          invalid={meta.touched && meta.error}
          {...field}
          {...props}
          type={showpass ? "text" : "password"}
        />
      )}
      <StyledIcon>{icon}</StyledIcon>
      {props.type === "password" && (
        <StyledIcon onClick={() => setShowpass(!showpass)} right>
          {showpass && <FiEye />}
          {!showpass && <FiEyeOff />}
        </StyledIcon>
      )}
      {meta.touched && meta.error ? (
        <ErrorMsg>{meta.error}</ErrorMsg>
      ) : (
        <ErrorMsg style={{ visibility: "hidden" }}>.</ErrorMsg>
      )}
      <Popup style={{visibility: "hidden"}}></Popup>    

    </div>
  );
};
  
4

2 回答 2

1

我没有得到 Popup 组件的定义位置,但它的想法应该是这样的:

const [showPopup, setShowPopup] = useState(true);

useEffect(() => {
  if (yourcondition meets criteria) {
    setShowPopup(!showPopup);
  }
}, [yourcondition]);


<Popup disabled={showPopup} ... />

这样,当“yourcondition”之类的依赖项(可能是来自 store、redux、Context、prop、另一个 state 等的某个值)发生变化时,它符合您想要的条件(例如 if (yourcondition === 'no' or whatever) { 或if (!yourcondition) { 等,然后 useEffect 将设置disabled(或者show,我不知道 Popup 组件道具)Popup 为假,如果它是真的。

于 2021-09-15T17:12:29.110 回答
1

你是在正确的方式。只需更改道具名称。

它是openonClose

<Popup open={show} onClose={() => setShow(false)}>

参考:https ://react-popup.elazizi.com/component-api

于 2021-09-15T17:15:43.640 回答