我正在尝试编写一个动态渲染按钮的方法,并试图通过使用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>
)
}
}
show = () => {Your Function Body}
这样的箭头函数{this.renderButtons()}
onPress={this.show(type)}
必须使用bind()
方法并传递this
关键字作为第一个参数onPress={this.show.bind(this, type)}