我有一个想要呈现的对话框。我需要一个箭头函数,它允许我调用我编写的回调 Prop 以及通过使用状态关闭模式屏幕。我可以关闭它,但不能调用父组件的回调
export class DialogBox extends PureComponent {
okButton = <Button type="text" title={t('action')} onPress={this.onOkPressed} />
cancelButton = <Button type="text" title={t('cancel')} onPress={this.onCancelPressed} />
confirmButtonBox = (
<Fragment>
{this.cancelButton}
{this.okButton}
</Fragment>
)
state = {
isVisible: this.props.isVisible,
}
onModalClose = () => {
this.setIsVisible(false)
}
onOkPressed = () => {
this.props.onOkPress()
this.onModalClose()
}
onCancelPressed = () => {
this.props.onCancelPress()
this.onModalClose()
}
setIsVisible (visible) {
this.setState({ isVisible: visible })
}
renderButtons (type) {
switch (type) {
case 'confirm':
return this.confirmButtonBox
case 'alert':
return this.okButton
default:
return this.okButton
}
}
render () {
const {
title, message, type,
} = this.props
return (
<Modal transparent animationType="fade" visible={this.state.isVisible}>
<View style={styles.container}>
<View style={styles.alertContainer}>
<View>
<Text>
<H3 style={{ fontWeight: 'bold' }}>
{title}
</H3>
</Text>
<Text>
{message}
</Text>
</View>
<View style={styles.buttons}>
{this.renderButtons(type)}
</View>
</View>
</View>
</Modal>
)
}
}
我需要它工作的方式是:
我有一个该组件外部的容器类,它允许用户在按“确定”和按“取消”时实现回调方法。
class DialogBoxStoryContainer extends PureComponent {
// state = { isVisible: false, type: 'confirm' }
onOkPressed = () => {
// this.setState({ isVisible: false })
console.debug('on ok pressed')
}
onCancelPressed = () => {
// this.setState({ isVisible: false })
console.debug('on cancel pressed')
}
render () {
return (
<View>
<DialogBox
{...this.props}
onOkPress={this.onOkPressed}
onCancelPress={this.onCancelPressed}
isVisible="true"
type="confirm"
/>
我没有看到这里执行的回调。我在这里缺少什么?
最佳答案
你的代码对我有用。如果 Chrome 中的“默认级别”(我假设您使用的是 Chrome)未设置为“详细”,则您将看不到 console.debug
输出。我不知道这个配置在 Firefox 或其他浏览器中的位置。因此,如果您使用的是其他设置,只需找到此设置即可。
关于javascript - 如何在 native react 中进行回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51934120/