我试图编写一种方法来动态呈现按钮,并试图通过使用renderButton方法来避免代码重复。对于这个问题,我找不到任何可靠的解决方案,任何人都可以帮忙?我是新来的本地人
export default class DialogBoxStory extends PureComponent {
state = { isVisible: false, type: 'confirm' }
hide (type) {
return (payload = '') => {
this.setState({ isVisible: false })
console.debug(`hide ${type}`, payload)
}
}
show (type) {
return (payload) => {
this.setState({ isVisible: true, type })
console.debug(`show ${type}`, payload)
}
}
renderButtons () {
return [ 'confirm', 'alert', 'input' ]
.map((type) => (
<Button
title={`show ${type} dialog`}
type="primary"
onPress={this.show(type)}
/>
))
}
render () {
const options = {
title: text('title', 'Test Title', 'props'),
message: text('message', lorem, 'props'),
onOkPress: this.hide('onOkPress'),
onCancelPress: this.hide('onCancelPress'),
isVisible: this.state.isVisible,
type: this.state.type,
onRequestClose: this.hide('onRequestClose'),
}
return (
<Fragment>
<DialogBox {...options} />
{this.renderButtons}
</Fragment>
)
}
}
答案 0 :(得分:1)
将所有方法(函数)声明转换为箭头函数,例如show = () => {Your Function Body}
您必须调用renderButtons函数{this.renderButtons()}
代码onPress={this.show(type)}
的这一部分还必须使用bind()
方法并将this
关键字作为第一个参数onPress={this.show.bind(this, type)}