这是我的 React 组件类 (ModalExampleControlled
):
class ModalExampleControlled extends React.Component {
state = {modalOpen: false}
handleOpen = () => this.setState({ modalOpen: true })
handleClose = () => this.setState({ modalOpen: false })
handleConfirm = () => {
this.handleClose()
this.props.delete(this.props.nome)
}
render() {
return (
<Modal
trigger={<Button onClick={this.handleOpen}>Show Modal</Button>}
open={this.state.modalOpen}
onClose={this.handleClose}
basic
size='small'
>
<Header icon='remove' content={'Elimina ' + this.props.nome}/>
<Modal.Content>
<p>
{this.props.testo}
</p>
</Modal.Content>
<Modal.Actions>
<Button basic color='grey' inverted onClick={this.handleClose}>
<Icon name='remove'/> Annulla
</Button>
<Button color='red' onClick={this.handleConfirm} inverted>
<Icon name='checkmark' /> Conferma
</Button>
</Modal.Actions>
</Modal>
)
}
}
我无法在 handleConfirm
方法中执行 this.props.delete(this.props.nome)
(我没有收到任何错误)。我只能在渲染 block 的 onClick
处理程序中执行此操作:
<Button color='red' onClick={this.props.delete(this.props.nome)} inverted>
<Icon name='checkmark' /> Conferma
但我需要在 props.delete()
调用上关闭模式。
父类delete
方法是这样的:
delete = quale => e => {
this.setState({
openModal: '',
loading: true,
status: 'In cancellazione '+quale+'...'
});
fetch(`${helper.get_url()}/api/delete?quale=${quale}`, {
method: 'get',
headers: {
'Content-Type': 'application/json'
}
}).then(r => r.json()).then(r => {
this.setState({
file: r.ok ? '\nEliminato: ' + quale +' ('+r.body.length+' righe)' : 'Error ' + quale,
loading: false
});
})
}
并且父类render方法包含子组件:
<ModalExampleControlled nome='prodotti' testo='Verranno eliminati i prodotti e il listino associato!'
delete={this.delete}/>
我已经尝试在构造中绑定(bind)我的 handleConfirm
但没有成功。
提前致谢。
最佳答案
delete = quale => e => {}
处理程序返回一个函数。
<Button color='red' onClick={this.props.delete(this.props.nome)} inverted>
以上之所以有效,是因为您正在调用该函数并传入 this.props.nome
(它返回一个接受 e
的函数)。
您可以像使用有效的内联按钮一样调用该函数,或者您也需要在 handleConfirm()
中调用返回函数。处理程序。
this.props.delete(quale)(e);
关于javascript - 我无法在事件处理程序中执行 props 父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50791729/