【问题标题】:Any way I can declare the event object rather than in the params of a function?有什么方法可以声明事件对象而不是函数的参数?
【发布时间】:2020-04-13 20:16:42
【问题描述】:

无论如何我可以将 e 对象放在 handleSubmit 函数中吗?我那里已经有一个参数,如果我将 e 添加到参数中,那么它将根据参数的顺序给我一个错误,如果 handleSubmit=(e, priorityLevelData)= 则说“TypeError:e.preventDefault 不是函数” > {。 .... 或“TypeError: Cannot read property 'preventDefault' of undefined” if handleSubmit=(priorityLevelData, e)=> {

    import React from "react";
    import PrioritySelector from "./PrioritySelector";
    import { connect } from "react-redux";

    class TodoForm extends React.Component {


        /*submit handler to grab input from the input references and store them
        in the "todoData" object. Then dispatches an action type and payload
        capturing the data. Then clears the input*/

        handleSubmit=(e, priorityLevelData)=> {
e.preventDefault()
            const todoTitle = this.getTodoTitle.value;
            const description = this.getDescription.value;
            const priorityLevel = priorityLevelData;
            const todoData = {
                id: Math.floor(Math.random()*1000),
                todoTitle,
                description,
                priorityLevel,
                editing: false
            }
            this.props.dispatch({type:"ADD_TODO", todoData })
            this.getTodoTitle.value = "";
            this.getDescription.value = "";

        }





        render() {
            console.log(this.props, "TODOFORMPROPS")
            return(
                <div>
                    <form onSubmit={this.handleSubmit}>
                        <input type="text" ref={(input)=> this.getTodoTitle=input} placeholder="Enter Todo" required/>
                        <input type="text" ref={(input)=> this.getDescription=input} placeholder="Enter Description" required/>
                        <PrioritySelector  getData={this.handleSubmit} />
                        <button>Add Todo</button>
                    </form>
                </div>
            )
        }
    }

    const mapStateToProps = (state) => {
        return {
            priorityLevel: state
        }
    }


    export default connect(mapStateToProps)(TodoForm);

【问题讨论】:

    标签: javascript reactjs react-native ecmascript-6


    【解决方案1】:

    这样做:

    <form onSubmit={e => this.handleSubmit(e)}>
    

    您还可以将任何其他附加数据传递给handleSubmit(),例如this.state

    <form onSubmit={e => this.handleSubmit(e, this.state)}>
    

    【讨论】:

      猜你喜欢
      • 2015-08-19
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多