简体   繁体   English

如何在ReactJS onSubmit函数调用上传入第二个参数

[英]How to pass in a second argument on ReactJS onSubmit function call

Here are the codes 这是代码

import React from "react";

var newForm = React.createClass({
    handleSubmit: function (e, text) {
        e.preventDefault();
        console.log(text);
    },
    render: function () {
        return (
            <form onSubmit={this.handleSubmit("react!!!")}>
                <input type="text"/>
            </form>
        );
    }
)};

module.exports = newForm;

What I want to achieve with this is that when I submit the form, I want the string "react!!!" 我想要实现的是当我提交表单时,我希望字符串“反应!!!” to be printed out in the console and prevent the default event from taking place at the same time. 在控制台中打印出来,防止默认事件同时发生。

Obviously, passing in the argument to "handleSubmit" function breaks the code. 显然,将参数传递给“handleSubmit”函数会破坏代码。

Is there anyway to pass in an argument from onSubmit event to the functions attached to this event? 无论如何将onSubmit事件中的参数传递给附加到此事件的函数?

You can curry the function 你可以咖喱这个功能

handleSubmit: text => event => {
  event.preventDefault()
  console.log(text)
}

<form onSubmit={this.handleSubmit('react!!!')}>
  ...

Equivalent ES5 code 等效的ES5代码

handleSubmit: function(text) {
  return function(event) {
    event.preventDefault()
    console.log(text)
  }.bind(this)
}

Your code is weird though because you're mixing ES6 and ES5 styles. 您的代码很奇怪,因为您正在混合使用ES6和ES5样式。 If you're using ES6 imports, you might as well use ES6 in the rest of your code 如果您正在使用ES6导入,那么您可以在其余代码中使用ES6

import {Component} from 'react'

class NewForm extends Component {
  handleSubmit (text) {
    return event => {
      event.preventDefault()
      console.log(text)
    }
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit('react!!!')}>
        <input type="text">
      </form>
    }
  }
}

export default NewForm

Or better, since your Component doesn't use any state, you can use a Stateless Functional Component 或者更好,因为您的Component不使用任何状态,您可以使用无状态功能组件

import {Component} from 'react'

const handleSubmit = text=> event=> {
  event.preventDefault()
  console.log(text)
}

const NewForm = props=> (
  <form onSubmit={handleSubmit('react!!!')}>
    <input type="text">
  </form>
)

export default NewForm

Yes, but you shouldn't do it. 是的,但你不应该这样做。 What you are currently doing is saying 'set the onSubmit handler to being the result of calling this.handleSubmit('react!!!')'. 你目前正在做的是说'将onSubmit处理程序设置为调用this.handleSubmit('react !!!')'的结果。 What would work instead is to go: 相反的是:

<form onSubmit={e => this.handleSubmit(e, "react!!!")}>

which is of course just the short form of saying: 这当然只是简短的说法:

<form onSubmit={function(e) { this.handleSubmit(e, "react!!!"); }}>

However, although this will work, what this is doing is defining a new anonymous function every time render is called. 但是,尽管这会起作用,但每次调用render时,这样做都是定义一个新的匿名函数。 Render can be called often, so this will end up with a bunch of new functions being created all the time, which can cause perf issues as they need to be garbage collected and cleaned up. 渲染可以经常调用,因此最终会创建一堆新函数,这可能会导致执行问题,因为它们需要进行垃圾回收和清理。

What is better is to have a function which is capable of finding the data you need on its own. 更好的是拥有一个能够自己找到所需数据的功能。 There are 2 different ways which I use to address this: 我用两种不同的方法来解决这个问题:

  • Either store the relevant data in props, so that it can be pulled out from this.props 将相关数据存储在props中,以便可以从this.props提取出来
  • Or, store the relevant data in the DOM (using HTML 5 data attributes ), and then pull them out using javascript. 或者,将相关数据存储在DOM中(使用HTML 5数据属性 ),然后使用javascript将其拉出。 Since you are given the event target in the event handler that is called, you can use it to pull out any data attributes you have stored. 由于在调用的事件处理程序中为您提供了事件目标,因此您可以使用它来提取已存储的任何数据属性。 For example you might declare your form like this: 例如,您可以声明您的表单如下:

    <form data-somefield={something.interesting} onSubmit={this.handleSubmit}>

which you could access in handleSubmit by going: 你可以通过以下方式访问handleSubmit:

handleSubmit: function(e) {
    console.log(e.target.dataset.somefield);
}

The caveat there being that a) storing data in the DOM like this doesn't feel very idiomatic React, and b) if you use this for onClick events with nested elements, you might find that you have to climb up the DOM hierarchy to find where your data is stored. 需要注意的是a)在DOM中存储数据这样的感觉并不是非常惯用的反应,而b)如果你将这个用于嵌套元素的onClick事件,你可能会发现你必须爬上DOM层次结构才能找到存储数据的位置。 As an example if you have a div with a data attribute and an onClick but it contains a span and an image, when you click the image it's possible that is what the onClick handler will see as it's target element, meaning you'd have to go up to the parent to find the div with the data attribute you're looking for. 例如,如果你有一个带有数据属性的div和一个onClick但是它包含一个span和一个图像,当你单击图像时,它可能是onClick处理程序将看到的目标元素,这意味着你必须转到父级查找具有您正在查找的数据属性的div。

So it's probably best to just include the data you want in your component's props and pull it out from there in your event handler. 因此,最好只在组件的道具中包含所需的数据,然后在事件处理程序中将其拉出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM