最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - react: how to set focus from a click handler - Stack Overflow

programmeradmin1浏览0评论

My react-redux based form has a button that should reset the form and move focus back to the first input field.
Resetting the content is straight up redux state, but I'm having trouble with the focus.

autoFocus on the first field works only on the initial render. Is there any sane way to re-trigger it?

If I need to go with explicit element.focus(), where should I call it from? I'm using react-redux, but not redux-forms.

My react-redux based form has a button that should reset the form and move focus back to the first input field.
Resetting the content is straight up redux state, but I'm having trouble with the focus.

autoFocus on the first field works only on the initial render. Is there any sane way to re-trigger it?

If I need to go with explicit element.focus(), where should I call it from? I'm using react-redux, but not redux-forms.

Share Improve this question edited Apr 12, 2016 at 13:52 Joachim Lous asked Apr 12, 2016 at 13:45 Joachim LousJoachim Lous 1,5511 gold badge17 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

Do you keep some info in store to know which element should get focus on page load? Nope? Then why you should do that later?

Trigger element.focus() right after dispatching action - you don't need Redux to achieve this, nor Redux to store this state.

Pseudocode could look like this

onReset() {
  const action = {
    type: RESET_FORM,
  }
  dispatch(action);

  const element = getElement(); // propably read ref? Find element with [autoFocus] attribute in ponent?
  element.focus();
}

you can use:

document.getElementById("ElementName").focus();

Final code here:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<script>
function change() {
    document.getElementById("two").focus();
}
</script>
</head>



<body>
    <input type="radio" name="name" id="name" onchange="change()" /> 

    <input type="text" name="one" id="one" /> 
    <input type="text" name="two" id="two" /> 
</body>
</html>

发布评论

评论列表(0)

  1. 暂无评论