按钮为什么打开相同的组件而不是打开每个按钮的各自组件?

huangapple go评论80阅读模式
英文:

Why do the buttons open the same component instead of opening each button each component?

问题

Sure, here is the translated content:

父组件

export const Messages = () => {

  const [showInfo, setShowInfo] = useState(false);
  

  return (
    <Stack>
       <Button
        onClick={() => setShowInfo(true)}
      >
        打开信息消息
      </Button>
      <InfoMessage open={showInfo} onClose={() => setShowInfo(false)} />
      <Button
        onClick={() =>  setShowInfo(true)}
      >
        打开成功消息
      </Button>
      <SuccessMessage open={showInfo} onClose={() =>  setShowInfo(false)} />
      <Button
        onClick={() =>  setShowInfo(true)}
      >
        打开错误消息
      </Button>
      <ErrorMessage open={showInfo} onClose={() =>  setShowInfo(false)} />
    </Stack>
  )
}

子组件(一个示例)

interface InfoMessageProps {
  open: boolean;
  onClose: () => void;
}

export const InfoMessage = ({ open, onClose }: InfoMessageProps) => {

  const handleClose = (): void => {
    onClose();
  };

 
  return (
    <Snackbar
      open={open}
      autoHideDuration={4000}
      anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
      onClick={handleClose}
      // TransitionComponent={transition}
    >
      <Alert
        sx={{
              width: '487px',
              height: '104px',
              paddingTop: '20px',
              paddingLeft: '20px',
              backgroundColor: '#FDFDFD',
        }}
        icon={false}
        action={(
          <IconButton
            aria-label="close"
            color="inherit"
            size="small"
            onClick={handleClose}
          >
            <CloseIcon fontSize="inherit" />
          </IconButton>
        )}
      >
        <AlertTitle sx={{ paddingRight:'80px' }}>
          <Typography variant='headings.h4'>标题</Typography>
        </AlertTitle>
        <Typography variant='captions.default'>在这里插入消息</Typography>
      </Alert>
    </Snackbar>
  );
};

请注意,我已经将代码中的 HTML 实体字符(如 &lt;&gt;)替换为相应的 JavaScript 标签(如 <>)以进行翻译。

英文:

I have one parent component with 3 buttons and 3 children components. Each button should open one component but with my code the 3 buttons open the same component when I click on the buttons.
The children components are in 3 different files and the parent component has one state. Can anyone tell me what's wrong in my code.
I pasted one child component example but they're 3 alerts.
Besides, my task for school specifies this: The state should have three values representing info, success and failed. How can I do it?

parent component

export const Messages = () =&gt; {
const [showInfo, setShowInfo] = useState(false);
return (
&lt;Stack&gt;
&lt;Button
onClick={() =&gt; setShowInfo(true)}
&gt;
open info message
&lt;/Button&gt;
&lt;InfoMessage open={showInfo} onClose={()=&gt; setShowInfo(false)} /&gt;
&lt;Button
onClick={() =&gt;  setShowInfo(true)}
&gt;
open success message
&lt;/Button&gt;
&lt;SuccessMessage open={showInfo} onClose={()=&gt;  setShowInfo(false)} /&gt;
&lt;Button
onClick={()=&gt;  setShowInfo(true)}
&gt;
open error message
&lt;/Button&gt;
&lt;ErrorMessage open={showInfo} onClose={() =&gt;  setShowInfo(false)} /&gt;
&lt;/Stack&gt;
)
}

Child component (one example)

interface InfoMessageProps {
open: boolean;
onClose: () =&gt; void;
}
export const InfoMessage = ({ open, onClose }: InfoMessageProps) =&gt; {
const handleClose = (): void =&gt; {
onClose();
};
return (
&lt;Snackbar
open={open}
autoHideDuration={4000}
anchorOrigin={{ vertical: &#39;top&#39;, horizontal: &#39;right&#39; }}
onClick={handleClose}
// TransitionComponent={transition}
&gt;
&lt;Alert
sx={{
width: &#39;487px&#39;,
height: &#39;104px&#39;,
paddingTop: &#39;20px&#39;,
paddingLeft: &#39;20px&#39;,
backgroundColor: &#39;#FDFDFD&#39;,
}}
icon={false}
action={(
&lt;IconButton
aria-label=&quot;close&quot;
color=&quot;inherit&quot;
size=&quot;small&quot;
onClick={handleClose}
&gt;
&lt;CloseIcon fontSize=&quot;inherit&quot; /&gt;
&lt;/IconButton&gt;
)}
&gt;
&lt;AlertTitle sx={{ paddingRight:&#39;80px&#39; }}&gt;
&lt;Typography variant=&#39;headings.h4&#39;&gt;title&lt;/Typography&gt;
&lt;/AlertTitle&gt;
&lt;Typography variant=&#39;captions.default&#39;&gt;Insert message here&lt;/Typography&gt;
&lt;/Alert&gt;
&lt;/Snackbar&gt;
);
};

答案1

得分: 1

我认为这可能是您的解决方案。

export const Messages = () => {

  const [msgStatus, setMsgStatus] = useState("");

  return (
    <Stack>
       <Button
        onClick={() => setMsgStatus("info")}
      >
        打开信息消息
      </Button>
      <InfoMessage open={msgStatus === "info"} onClose={() => setMsgStatus("")} />
      <Button
        onClick={() =>  setMsgStatus("success")}
      >
        打开成功消息
      </Button>
      <SuccessMessage open={msgStatus === "success"} onClose={() =>  setMsgStatus("")} />
      <Button
        onClick={() =>  setMsgStatus("error")}
      >
        打开错误消息
      </Button>
      <ErrorMessage open={msgStatus === "error"} onClose={() =>  setMsgStatus("")} />
    </Stack>
  )
}

希望这能帮助您。

英文:

I think it could be your solution

export const Messages = () =&gt; {
const [msgStatus, setMsgStatus] = useState(&quot;&quot;);      
return (
&lt;Stack&gt;
&lt;Button
onClick={() =&gt; setMsgStatus(&quot;info&quot;)}
&gt;
open info message
&lt;/Button&gt;
&lt;InfoMessage open={msgStatus === &quot;info&quot;} onClose={()=&gt; setMsgStatus(&quot;&quot;)} /&gt;
&lt;Button
onClick={() =&gt;  setMsgStatus(&quot;success&quot;)}
&gt;
open success message
&lt;/Button&gt;
&lt;SuccessMessage open={msgStatus === &quot;success&quot;} onClose={()=&gt;  setMsgStatus(&quot;&quot;)} /&gt;
&lt;Button
onClick={()=&gt;  setMsgStatus(&quot;error&quot;)}
&gt;
open error message
&lt;/Button&gt;
&lt;ErrorMessage open={msgStatus === &quot;error&quot;} onClose={() =&gt;  setMsgStatus(&quot;&quot;)} /&gt;
&lt;/Stack&gt;
)
}

答案2

得分: 0

因为你应该为每个组件使用不同的状态。发生这种情况是因为showInfo为true,每个组件都被渲染并重叠在一起。

编辑:

你可以更改你的onClick函数,并添加一个条件来渲染每个组件:

英文:

Because you should use different states for each component. What's happening is because showInfo is true, every component is being rendered and overlapping with each other.

EDIT:

You can change your onClick function and have a condition to render each component:

export const Messages = () =&gt; {
const [showInfo, setShowInfo] = useState(false);
const [conditionalState,setConditionState] =useState(false);
const setShow = (value) =&gt; {
setShowInfo(true);
setConditionState(value);
}
return (
&lt;Stack&gt;
&lt;Button
onClick={() =&gt; {setShow(0)}
&gt;
open info message
&lt;/Button&gt;
{conditionalState === 0 &amp;&amp; 
&lt;InfoMessage open={showInfo} onClose={()=&gt; setShowInfo(false)} /&gt;
}
&lt;Button
onClick={() =&gt; {setShow(1)}
&gt;
open success message
&lt;/Button&gt;
{conditionalState === 1 &amp;&amp; 
&lt;SuccessMessage open={showInfo} onClose={()=&gt;  setShowInfo(false)} /&gt;
}
&lt;Button
onClick={() =&gt; {setShow(2)}
&gt;
open error message
&lt;/Button&gt;
{conditionalState === 2 &amp;&amp; 
&lt;ErrorMessage open={showInfo} onClose={() =&gt;  setShowInfo(false)} /&gt;
}
&lt;/Stack&gt;
)
}

答案3

得分: 0

需要在您的代码中进行一个小的修正。您应该在parent.js中为不同的警报状态创建不同的状态,就像这样:

export const Messages = () => {

  const [showStatus, setShowStatus] = useState("");

  return (
    <Stack>
       <Button
        onClick={() => setShowStatus("info")}
      >
        打开信息消息
      </Button>
      <InfoMessage open={showStatus === "info"} onClose={() => setShowStatus("")} />
      <Button
        onClick={() =>  setShowStatus("success")}
      >
        打开成功消息
      </Button>
      <SuccessMessage open={showStatus === "success"} onClose={() =>  setShowStatus("")} />
      <Button
        onClick={() =>  setShowStatus("error")}
      >
        打开错误消息
      </Button>
      <ErrorMessage open={showStatus === "error"} onClose={() =>  setShowStatus("")} />
    </Stack>
  )
}

请注意,我只翻译了您提供的代码部分,没有添加其他内容。

英文:

A minor correction is needed in your code.
You should have different states for different alerts in your parent.js like this :

export const Messages = () =&gt; {
const [showStatus, setShowStatus] = useState(&quot;&quot;);
return (
&lt;Stack&gt;
&lt;Button
onClick={() =&gt; setShowStatus(&quot;info&quot;)}
&gt;
open info message
&lt;/Button&gt;
&lt;InfoMessage open={showStatus==&quot;info&quot;} onClose={()=&gt; setShowStatus(&quot;&quot;)} /&gt;
&lt;Button
onClick={() =&gt;  setShowStatus(&quot;success&quot;)}
&gt;
open success message
&lt;/Button&gt;
&lt;SuccessMessage open={showStatus == &quot;success&quot;} onClose={()=&gt;  setShowStatus(&quot;&quot;)} /&gt;
&lt;Button
onClick={()=&gt;  setShowStatus(&quot;error&quot;)}
&gt;
open error message
&lt;/Button&gt;
&lt;ErrorMessage open={showStatus==&quot;error&quot;} onClose={() =&gt;  setShowStatus(&quot;&quot;)} /&gt;
&lt;/Stack&gt;
)
}

huangapple
  • 本文由 发表于 2023年5月17日 14:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定