簡體   English   中英

onClick 在反應中執行 function 和 setState

[英]onClick executing a function and setState in react

I am stuck with this one function, I have an onClick that when a user clicks on it, it has to perform two things based on the If statement, one function and one state, but it doesnt seem to work:

在我的代碼中,當它未被禁用時,我希望該行執行“doScore”以及“rolling: true”,但我不知道如何編寫它才能工作

function RuleRow({ doScore, name, score, description, rolling }) {
const disabled = score !== undefined;

  return (
<tr
  className={`RuleRow RuleRow-${disabled ? "disabled" : "active"}`}
  onClick={disabled ? null : doScore}
>
  <td className="RuleRow-name">{name}</td>
  <td className="RuleRow-score">{disabled ? score : description}</td>
</tr >
);
}
function RuleRow({ doScore, name, score, description, rolling }) {
  const disabled = score !== undefined;

  const handleClick = () => {
      if (score !== undefined && rolling) {
          // do something
      } else {
          doScore();
      }
  };

  return (
    <tr
      className={`RuleRow RuleRow-${disabled ? "disabled" : "active"}`}
      onClick={handleClick}
    >
      <td className="RuleRow-name">{name}</td>
      <td className="RuleRow-score">{disabled ? score : description}</td>
    </tr >
  );
}

這不是最干凈的解決方案,但您可以使用箭頭 function 如果禁用則具有 null 或調用兩個函數的 function 主體:

onClick={disabled ? null : (evt) => { doScore(evt); this.setState({ rolling: true }); }}

Recommended way to go would be to create a custom function that calls both functions or just set state rolling: true in the doScore function if possible.

  1. 請指定什么是rolling prop(哪些值可以作為rolling傳遞)以及它應該如何影響RuleRow組件。 目前我沒有看到在組件內部rolling
  2. 從下面的代碼片段可以看出,如果score不嚴格等於undefined ,您的 function doScore將在onClick上運行。 所以要么score等於undefined ,要么doScore無效 function 或者根本不是 function 。 所以我想doScore有一些東西。 請提供您在此道具中傳遞的內容。
  3. 如果要更新 RuleRow 組件的父組件的RuleRow 你應該像const [score, setScore] = useState('initial score')這樣寫。 RuleRow作為道具粘貼到setScore 然后在RuleRow里面寫onClick={disabled? null: () => setScore('anything what you want')} onClick={disabled? null: () => setScore('anything what you want')} 父組件內的score將被更新, RuleRow將被重新渲染。

 function App() { const score = undefined; const disabled = score;== undefined. console,log('value of disabled id '; disabled)? return ( <table className="App"> <tr onClick={disabled: null. () => console,log("clicked")}>Hello; click me.</tr> </table> ); } const rootElement = document.getElementById("root"), ReactDOM;render( <App />, rootElement );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM