![](/img/trans.png)
[英]onError img function is not working/triggered in React component
[英]Button is not triggered in react component
我是新手,我不明白為什么簡單的按鈕不起作用。
export default class PlayerList extends Component {
constructor(props) {
super(props)
this.state = {
players: [],
convocPlayers: []
}
this.sendConvoc = this.sendConvoc.bind(this)
}
async sendConvoc() {
try {
let data = this.state.convocPlayers;
await axios.post('/players/convoc', {
players: data
});
} catch (error) {
alert(error)
}
}
render() {
return (
<div>
<PlayerForm addPlayer={(user) => this.addPlayer(user)}></PlayerForm>
</div>
<div className="flex items-center justify-between mt-8">
<span className="text-3xl">Liste des joueurs</span>
<PrimaryButton onClick={() => this.sendConvoc}>Envoyer la convocation</PrimaryButton>
</div>
)
}
}
我的 PrimaryButton 組件:
export default class PrimaryButton extends React.Component {
render () {
return (
<button type={this.props.type} onClick={() => this.onClick} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
{this.props.children}
</button>
)
}
onClick() {
var clickFunction = this.props.onClick || null;
if (clickFunction) {
clickFunction()
}
}
}
當我點擊“PrimaryButton”時,sendConvoc函數永遠不會觸發,如果有人有解決方案,請提前謝謝
您應該將 onClick 函數更改為onClick={() => this.onClick()}
或僅onClick={this.onClick}
我們必須明白為什么你的函數沒有被觸發。 當我們指定一個事件,即onClick
時,React 期望我們傳遞一個函數而不是調用該函數。
✅ 正確 - 傳遞一個函數
<PrimaryButton onClick={this.sendConvoc}>
// passing an inline function
<PrimaryButton onClick={() => this.sendConvoc()}>
<PrimaryButton onClick={() => alert('hello')}>
對於內聯函數,注意我們需要調用里面的函數,否則內聯函數會返回函數定義(不是調用函數)。
❌ 不正確 - 調用函數
<PrimaryButton onClick={this.sendConvoc()}>
<PrimaryButton onClick={alert('hello')}>
對於您的情況, PrimaryButton
組件中的解決方案是調用內聯函數中的函數。 此外,我們可能不需要一個更簡單的解決方案的內聯函數。
// BEFORE
// the issue here is we forgot to call `this.onClick`, we return function definition of `this.onClick` here.
<button type={this.props.type} onClick={() => this.onClick}
// AFTER
<button type={this.props.type} onClick={() => this.onClick()}
// or
<button type={this.props.type} onClick={this.onClick} // simpler
在PlayerList
組件中
// BEFORE
<PrimaryButton onClick={() => this.sendConvoc}>
// AFTER
<PrimaryButton onClick={() => this.sendConvoc()}>
// or
<PrimaryButton onClick={this.sendConvoc}>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.