对象作为反应子错误无效。找到带键的对象()

问题描述 投票:1回答:1

我正在尝试编写一个动态渲染按钮的方法,并试图通过使用renderButton方法避免代码重复。我无法找到一个可靠的解决方案,任何人都可以帮助这个问题吗?我很反应原生

enter image description here

   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>
    )
  }
}
javascript reactjs react-native ecmascript-6
1个回答
1
投票
  • 将所有方法(函数)声明转换为像show = () => {Your Function Body}这样的箭头函数
  • 你必须调用你的renderButtons函数{this.renderButtons()}
  • 此部分代码onPress={this.show(type)}必须使用bind()方法并传递this关键字作为第一个参数onPress={this.show.bind(this, type)}

Read more about bind() method

© www.soinside.com 2019 - 2024. All rights reserved.