如何在函数组件中设置if条件内的状态。

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

How to set states inside ifcondition in functional component

问题

setEditOnClick(true)的中文翻译是setEditOnClick(true)`。

你的代码如下:

const peopleCard = () => {
 const [isEditOnclick, setEditOnClick] = useState(false);
 const [peopleID, setpeopleID] = useState('');

 return (
 .....
 .....其他一些代码
 .....

 {isEditOnclick ? 

    <CrudModal id={peopleID} />
    {setEditOnClick(false)}
     
    : null }

 }

 ......
 ......
 <button onMouseEnter={() => setEditOnClick(true)}}

希望这可以帮助你解决问题。

英文:

How to set setEditOnClick(true) on condition inside functional component

const peopleCard = () =&gt; {
 const [isEditOnclick, setEditOnClick] = useState(false);
 const [peopleID, setpeopleID] = useState(&#39;&#39;);
return (
.....
.....some other code
.....

 {isEditOnclick ? 

    &lt;CrudModal id={peopleID} /&gt;
    {setEditOnClick(false)}
     
    : null }

}

......
......
 &lt;button onMouseEnter={() =&gt; setEditOnClick(true)}}

Am new to react kindly help me to fix this

答案1

得分: 0

你不应该在你的JSX代码中设置状态'setEditOnClick(true)',因为这实际上会取消渲染CrudModal组件。相反,你应该执行以下操作:

const PeopleCard = () => {
  const [isEditOnclick, setEditOnClick] = useState(false);
  const [peopleID, setpeopleID] = useState('');

  // 定义一个处理按钮的鼠标进入事件的函数
  // 检查isEditOnclick当前是否为false
  // 使用setEditOnClick函数将isEditOnclick设置为true
  const handleMouseEnter = () => {
    if (!isEditOnclick) {
      setEditOnClick(true);
    }
  };

  // 渲染组件的JSX代码
  return (
    <>
      {/* 一些其他代码 */}
      {isEditOnclick && <CrudModal id={peopleID} />}
      {/* 一些其他代码 */}
      <button onMouseEnter={handleMouseEnter}>Edit</button>
    </>
  );
};
英文:

You should not set the state 'setEditOnClick(true)' inside your JSX code because you are basically unrendering the CrudModal component. Instead, you should do the following:

    const PeopleCard = () =&gt; {
      const [isEditOnclick, setEditOnClick] = useState(false);
      const [peopleID, setpeopleID] = useState(&#39;&#39;);
    
      // Define a function to handle the mouse enter event on the button
      // Check if isEditOnclick is currently false
      // Set isEditOnclick to true using the setEditOnClick function
      const handleMouseEnter = () =&gt; {
        if (!isEditOnclick) {
          setEditOnClick(true);
        }
      };
    
      // Render the component&#39;s JSX code
      return (
        &lt;&gt;
          {/* some other code */}
          {isEditOnclick &amp;&amp; &lt;CrudModal id={peopleID} /&gt;}
          {/* some other code */}
          &lt;button onMouseEnter={handleMouseEnter}&gt;Edit&lt;/button&gt;
        &lt;/&gt;
      );
    };

huangapple
  • 本文由 发表于 2023年4月13日 22:57:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006940.html
匿名

发表评论

匿名网友

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

确定