English 中文(简体)
如何提交反应中采用进入钥匙的形式?
原标题:How to submit a form using Enter key in react.js?

这里是我的形式和浮标方法。 当关键板进入纽顿时,我想执行这种方法。 如何?

N.B:No jquery.

comment: function (e) {
  e.preventDefault();
  this.props.comment({
    comment: this.refs.text.getDOMNode().value,
    userPostId:this.refs.userPostId.getDOMNode().value,
  })
},


<form className="commentForm">
  <textarea rows="2" cols="110" placeholder="****Comment Here****" ref="text"  /><br />
  <input type="text" placeholder="userPostId" ref="userPostId" /> <br />
  <button type="button" className="btn btn-success" onClick={this.comment}>Comment</button>
</form>
最佳回答

更改<代码><丁顿类型=“button”至<丁顿类型=“submit”。 删除<代码>onClick。 相反,在Submit={Form Submit}>。 这应当点击 but子,迫使返回钥匙。

const onFormSubmit = e => {
  e.preventDefault();
  // send state to server with e.g. `window.fetch`
}

...

<form onSubmit={onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>

Full example without any silly form libraries:

function LoginForm() {
  const [email, setEmail] = useState(  )
  const [password, setPassword] = useState(  )
  const [submitting, setSubmitting] = useState(false)
  const [formError, setFormError] = useState(  )

  const onFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    try {
      e.preventDefault();
      setFormError(  )
      setSubmitting(true)
      await fetch(/*POST email + password*/)
    } catch (err: any) {
      console.error(err)
      setFormError(err.toString())
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <form onSubmit={onFormSubmit}>
      <input type="email" autoComplete="email" value={email} onChange={e => setEmail(e.currentTarget.value)} required />
      <input type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.currentTarget.value)} required />
      {Boolean(formError) &&
        <div className="form-error">{formError}</div>
      }
      <button type="submit" disabled={submitting}>Login</button>
    </form>
  )
}

P.S. Remember that any buttons in You form which should not submission the form should express have type="button”.

问题回答

It s been quite a few years since this question was last answered. React introduced "Hooks" back in 2017, and "keyCode" has been deprecated.

我们现在可以这样做:

  useEffect(() => {
    const listener = event => {
      if (event.code === "Enter" || event.code === "NumpadEnter") {
        console.log("Enter key was pressed. Run your function.");
        event.preventDefault();
        // callMyFunction();
      }
    };
    document.addEventListener("keydown", listener);
    return () => {
      document.removeEventListener("keydown", listener);
    };
  }, []);

This registers a listener on the keydown event, when the component is loaded for the first time. It removes the event listener when the component is destroyed.

this is how you do it if you want to listen for the "Enter" key. There is an onKeydown prop that you can use and you can read about it in react doc

https://codesand Box.io/s/new?fontsize=14&hidenavigation=1&theme=dark”rel=“noreferer”>codeSand Box

const App = () => {
    const something=(event)=> {
        if (event.keyCode === 13) {
            console.log( enter )
        }
    }
return (
    <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <input  type= text  onKeyDown={(e) => something(e) }/>
    </div>
);
}

使用<条码> 活动:

   input: HTMLDivElement | null = null;

   onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
      //  keypress  event misbehaves on mobile so we track  Enter  key via  keydown  event
      if (event.key ===  Enter ) {
        event.preventDefault();
        event.stopPropagation();
        this.onSubmit();
      }
    }

    onSubmit = (): void => {
      if (input.textContent) {
         this.props.onSubmit(input.textContent);
         input.focus();
         input.textContent =   ;
      }
    }

    render() {
      return (
         <form className="commentForm">
           <input
             className="comment-input"
             aria-multiline="true"
             role="textbox"
             contentEditable={true}
             onKeyDown={this.onKeyDown}
             ref={node => this.input = node} 
           />
           <button type="button" className="btn btn-success" onClick={this.onSubmit}>Comment</button>
         </form>
      );
    }
import React, { useEffect, useRef } from  react ;

function Example() {

    let inp = useRef();
    useEffect(() => {
        if (!inp && !inp.current) return;
        inp.current.focus();
        return () => inp = null;
    });

    const handleSubmit = () => {
        //...
    }

    return (
        <form
            onSubmit={e => {
                e.preventDefault();
                handleSubmit(e);
            }}
        >
            <input
                name="fakename"
                defaultValue="...."
                ref={inp}
                type="radio"
                style={{
                    position: "absolute",
                    opacity: 0
                }}
            />
            <button type="submit">
                submit
            </button>
        </form>
    )
}

有时,由于表格可能没有任何投入,因此它不会仅仅约束一种形式,而将提交表格通过。

在这种情况下,如果您通过<编码>文件将活动与文件联系起来,就会在申请的另一部分造成问题。

为了解决这个问题,我们应该总结一个形式,并应当提出由 c所掩盖的内容,然后,你将注意力放在这一投入上,将正确工作。

If you don t have the form inside <form>, you could use this in componentDidMount():

componentDidMount = () => {
      document.addEventListener("keydown", (e) => 
        e.code === "Enter" && console.log("my function"))
    }
    
componentDidMount() //<-- remove this, it s just for testing here
useEffect(() => {
const keyEnter = event => {
      if (event.key ===  Enter ) {
        event.preventDefault()
      }
    }

    document.addEventListener( keydown , keyEnter)

    return () => {
      document.removeEventListener( keydown , keyEnter)
    }
    }, [])

I have found this to be easier. Listen for the keyDown event on the input you want to submit by pressing Enter" key and handle the submit action with conditional ternary operator as show below in a single line.
This is mostly used on subscribing a newsletter where there s no need of a button to submit. Hope it helps.

<input 
     type="email" 
     placeholder="Email" 
     onKeyDown={e => e.key ===  Enter  ? handleSubmit :   } />

您可使用<代码><button打字=提交和开发;</button>,在中间无。

www.un.org/Depts/DGACM/index_spanish.htm 你们只能改变纽子类 = 和;但必须提交。

    <form
        onSubmit={e => {
            e.preventDefault();
            handleSubmit(e);
        }}
       >
        <input
            name="developers"
            defaultValue="submit"
            ref={dev}
            type="radio"
        />
        <button type="submit">
            submit
        </button>
    </form>

在这里,非常选择的法典

useEffect(() => {
    document
        .getElementById("Your-element-id")
        .addEventListener("keydown", function (event) {
            if (event.code === "Enter" || event.code === "NumpadEnter") {
                event.preventDefault();
                document.getElementById("submit-element").click();
            }
        });
}, []);

use mousetrap
https://www.npmjs.com/package/mousetrap
https://www.npmjs.com/package/@types/mousetrap
(yeah, I know, unfortunatelly when You use typescript u have to install types aside from basic module)

import {bind} from  mousetrap ;

const handleSubmit = async () => {
// submit func here
};

bind([ enter ,  return ], handleSubmit);

可能为了其他目的使用 mo装置的其他例子:

bind([ command+k ,  ctrl+k ], function(e) {
    highlight([11, 12, 13, 14]);
    return false;
});

因此,我正在围绕同一假设情景寻求某种解决办法,即,在用户打到键盘进入纽顿之后,在日志上,应启动日志。

你可以把案文箱与一部法典混为一谈,

<input
  // rest your code
  onKeyPress={ onkeyup }
/>

请铭记我正在使用反应灯来做到这一点,但这一链接将有助于你了解更多

您可以处理该问题。

   onKeyPress={e => e.key ===  Enter  && handleFormSubmit}

Try this:

const enterKye=()=>{
if(e.key==="Enter"){
  alert("hello");
  }
}
<input type="text" onKeyPress={enterKye}>

例如,下一期“React+TS”法(为州等添加“灯”):


type Props = {
...any properties
} & [any other type if need]

//I want notice that input data type of component maybe difference from type of props
const ExampleComponent: React.FC<Props> = (props: [Props or any other type]){
     const anySerice = new AnyService();

     const handleSubmit = async (eventForm) => {
        await anySerice.signUp();
     }

     const onKeyUp = (event: KeyboardEvent) => {
        //you can stay first condition only
        if (event.key ===  Enter  || event.charCode === 13) { 
            handleSubmit(event)
        }
    } 
    
    ...other code
    
    return (<Form noValidate validated={validated} className="modal-form-uthorize" onKeyPress={onKeyUp}>

    ...other components form

    </Form>)
}

export default ExampleComponent;




相关问题
How to use one react app into another react app?

I have two react apps, parent app and child app. and child app have an hash router. I have build the child app using npm run build, It creates build folder. That build folder moved into inside the ...

how to get selected value in Ant Design

I want to print the selected value, and below is my option list: const vesselName = [ { value: 0 , label: ALBIDDA , }, { value: 1 , label: ALRUMEILA , }, { value: 2 ,...

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings No results and Please try another search term. . I have tried No results.<br>Please try another search term. but ...

热门标签