【问题标题】:Error passing a selected value to a function将所选值传递给函数时出错
【发布时间】:2019-06-27 05:08:48
【问题描述】:

我有以下显示测验选项的组件,当用户选择一个值时,我想传递在“handleNext”中选择的“item.id”,没有 código abaixo aparece o seguinte erro:

Uncaught ReferenceError: item is not defined

代码:

render () {
    return (
        <UserContext.Provider value={this.state}>
            <UserContext.Consumer>
                {({ current_statement, current_alternative, handleNext}) => (

                   <form>
                        <p>{current_statement}</p>

                        {this.state.current_alternative.map(item => (
                            <React.Fragment key={item.id}>
                                <div>
                                    <input id={item.id} type="radio" name="question"/>
                                    <label htmlFor={item.id}>{item.content}</label>
                                </div>
                            </React.Fragment>
                        ))}

                        <button onClick={(e) => this.handleNext(e, item.id)} type="button">Next</button>

                    </form>
                )}

            </UserContext.Consumer>
        </UserContext.Provider>
    )
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    问题是你的下一步按钮的绑定:

    this.handleNext(e, item.id)
    

    您已在 .map() 函数的外部添加了此函数,因此没有 item(这是在 this.state.current_alternative 映射的每个循环中明确定义的)。把它移到.map()数组里面,你就可以访问item了。

    【讨论】:

    • 我只能放在.map ()里面但是按钮每次都重复,我怎么只能重复一个?
    • 我假设你想要最后一个item.id?使用this.handleNext(e, this.state.current_alternative[this.state.current_alternative.length - 1].id)
    • 内图,也可以试试this
    • 不是最后一个,我给用户5个选项,我要他在表单中选择的那个的id
    • 是一个测验,它有 5 个选项,当它点击“下一步”时,我想保存选定的选项
    【解决方案2】:
      handleRadioChange = id => this.setState({selected: id})
    
      render() {
        ...
        <input id={item.id} type="radio" name="question" onChange={e => this.handleRadioChange(e.event.target.id)} />
        ...
    
        <button onClick={(e) => this.handleNext(e, this.state.selected)} type="button">Next</button>
    

    简而言之: 您必须将用户选择的单选按钮的选定 id 存储在状态中,然后当用户按下它时,您的按钮将从状态中获取 id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      相关资源
      最近更新 更多