[英]Why can't I access my functional component's props within an event handler?
[英]I can't execute a props parent method inside an event handler
这是我的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)
(我没有得到任何错误)。 我只能在render块的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}/>
我已经尝试将我的handleConfirm
绑定到构造中,但没有成功。
提前致谢。
delete = quale => e => {}
处理程序将返回一个函数。
<Button color='red' onClick={this.props.delete(this.props.nome)} inverted>
上面的方法起作用是因为您正在调用该函数并传递this.props.nome
(该函数返回接受e
的函数)。
您可以像使用有效的内联按钮那样调用函数,也需要在handleConfirm()
处理程序中handleConfirm()
return函数。
this.props.delete(quale)(e);
delete函数返回一个函数,因此要执行该函数,您需要像这样调用它
handleConfirm = (e) => {
this.handleClose()
this.props.delete(this.props.nome)(e)
}
它在onClick={this.props.delete(this.props.nome)}
情况下起作用,因为onClick接受一个函数,并且this.props.delete(this.props.nome)
返回一个函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.