[英]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.
rolling
prop(哪些值可以作為rolling
傳遞)以及它應該如何影響RuleRow
組件。 目前我沒有看到在組件內部rolling
。score
不嚴格等於undefined
,您的 function doScore
將在onClick
上運行。 所以要么score
等於undefined
,要么doScore
無效 function 或者根本不是 function 。 所以我想doScore
有一些東西。 請提供您在此道具中傳遞的內容。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.