渲染后将焦点放在输入上

JavaScript

Near西里泡芙

2020-03-09

呈现组件后,将焦点设置在特定文本字段上的反应方式是什么?

文档似乎建议使用引用,例如:

ref="nameInput"在渲染函数中的输入字段上进行设置,然后调用:

this.refs.nameInput.getInputDOMNode().focus(); 

但是我应该在哪里称呼它呢?我已经尝试了几个地方,但无法正常工作。

第316篇《渲染后将焦点放在输入上》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

19个回答
古一梅 2020.03.09

由于造成此错误的原因很多,我认为我也应该发布我面临的问题。对我来说,问题在于我将输入内容渲染为另一个组件的内容。

export default ({ Content }) => {
  return (
  <div className="container-fluid main_container">
    <div className="row">
      <div className="col-sm-12 h-100">
        <Content />                                 // I rendered my inputs here
      </div>
    </div>
  </div>
  );
}

这就是我调用上述组件的方式:

<Component Content={() => {
  return (
    <input type="text"/>
  );
}} />
TonyMandy 2020.03.09

根据更新的语法,可以使用 this.myRref.current.focus()

老丝泡芙 2020.03.09

更新版本可以在这里查看

componentDidMount() {

    // Focus to the input as html5 autofocus
    this.inputRef.focus();

}
render() {
    return <input type="text" ref={(input) => { this.inputRef = input }} />
})
达蒙伽罗Tom 2020.03.09

阅读几乎所有答案,但没有看到 getRenderedComponent().props.input

设置文本输入参考

this.refs.username.getRenderedComponent().props.input.onChange('');

HarryL梅 2020.03.09

最简单的答案是在输入文本元素中添加ref =“ some name”并调用以下函数。

componentDidMount(){
   this.refs.field_name.focus();
}
// here field_name is ref name.

<input type="text" ref="field_name" />
村村宝儿Itachi 2020.03.09

我有同样的问题,但我也有一些动画,所以我的同事建议使用window.requestAnimationFrame

这是我元素的ref属性:

ref={(input) => {input && window.requestAnimationFrame(()=>{input.focus()})}}
留姬 2020.03.09

警告:ReactDOMComponent:不要访问DOM节点的.getDOMNode()。而是直接使用该节点。此DOM节点由渲染App

应该

componentDidMount: function () {
  this.refs.nameInput.focus();
}
小小 2020.03.09

要将焦点移到新创建的元素上,可以将元素的ID存储在状态中,并使用它来设置autoFocus例如

export default class DefaultRolesPage extends React.Component {

    addRole = ev => {
        ev.preventDefault();
        const roleKey = this.roleKey++;
        this::updateState({
            focus: {$set: roleKey},
            formData: {
                roles: {
                    $push: [{
                        id: null,
                        name: '',
                        permissions: new Set(),
                        key: roleKey,
                    }]
                }
            }
        })
    }

    render() {
        const {formData} = this.state;

        return (
            <GridForm onSubmit={this.submit}>
                {formData.roles.map((role, idx) => (
                    <GridSection key={role.key}>
                        <GridRow>
                            <GridCol>
                                <label>Role</label>
                                <TextBox value={role.name} onChange={this.roleName(idx)} autoFocus={role.key === this.state.focus}/>
                            </GridCol>
                        </GridRow>
                    </GridSection>
                ))}
            </GridForm>
        )
    }
}

这样,所有文本框都不会集中在页面加载上(就像我想要的那样),但是当您按下“添加”按钮来创建新记录时,该新记录就会获得焦点。

由于autoFocus除非重新安装该组件,否则它不会再次“运行”,因此我不必费心设置this.state.focus(即在更新其他状态时,它将不会继续窃取焦点)。

Green逆天 2020.03.09

AutoFocus最适合我。我需要双击将某些文本更改为带有该文本的输入,所以最终得到的结果是:

<input autoFocus onFocus={this.setCaretToEnd} value={this.state.editTodo.value} onDoubleClick={this.updateTodoItem} />

注:要解决React将插入号放置在文本开头的问题,请使用以下方法:

setCaretToEnd(event) {
    var originalText = event.target.value;
    event.target.value = '';
    event.target.value = originalText;
}

在这里找到:https : //coderwall.com/p/0iz_zq/how-to-put-focus-at-the-end-of-an-input-with-react-js

JinJin猪猪 2020.03.09

您可以将该方法调用放入render函数中。或在生命周期方法中,componentDidUpdate

NearPro 2020.03.09

这是自动对焦的正确方法。当使用回调而不是字符串作为参考值时,将自动调用它。您可以获得参考,而不需要使用来接触DOM。getDOMNode

render: function() {
  return <TextInput ref={(c) => this._input = c} />;
},
componentDidMount: function() {
  this._input.focus();
},
蛋蛋猿 2020.03.09

请注意,对于material-ui TextField组件,这些答案均不适合我如何将焦点设置为materialUI TextField?我必须跳过一些箍才能使它起作用:

const focusUsernameInputField = input => {
  if (input) {
    setTimeout(() => {input.focus()}, 100);
  }
};

return (
  <TextField
    hintText="Username"
    floatingLabelText="Username"
    ref={focusUsernameInputField}
  />
);
前端Mandy 2020.03.09

这不再是最佳答案。从v0.13 this.refs开始componentDidMount(),在某些奇怪的情况下,AFTER 运行之后可能不可用

只需将autoFocus标签添加到您的输入字段中,如上面的FakeRainBrigand所示。

Monkey洋 2020.03.09

参考 @Dave对@Dhiraj答案的评论;一种替代方法是在要渲染的元素上使用ref属性的回调功能(在组件首次渲染之后):

<input ref={ function(component){ React.findDOMNode(component).focus();} } />

更多信息

Harry逆天Eva 2020.03.09

如果您只想在React中进行自动对焦,那很简单。

<input autoFocus type="text" />

如果您只是想知道将代码放在哪里,答案在componentDidMount()中。

v014.3

componentDidMount() {
    this.refs.linkInput.focus()
}

在大多数情况下,您可以将ref附加到DOM节点,而完全避免使用findDOMNode。

在此处阅读API文档:https : //facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode

小胖A 2020.03.09

现在,React文档中有一节。https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute

 render: function() {
  return (
    <TextInput
      ref={function(input) {
        if (input != null) {
          input.focus();
        }
      }} />
    );
  },
GOItachi老丝 2020.03.09

从React 0.15开始,最简洁的方法是:

<input ref={input => input && input.focus()}/>
老丝泡芙 2020.03.09

@Dhiraj的答案是正确的,为方便起见,您可以使用autoFocus道具在安装时让输入自动聚焦:

<input autoFocus name=...

请注意,在jsx中,它autoFocus(大写F)与不区分大小写的普通旧html不同。

乐猪猪 2020.03.09

专注于坐骑

如果只想在挂载(初始渲染)时聚焦某个元素,则只需使用autoFocus属性即可。

<input type="text" autoFocus />

动态焦点

要动态控制焦点,请使用常规功能来隐藏组件的实现细节。

React 16.8 +功能组件-useFocus挂钩

const FocusDemo = () => {

    const [inputRef, setInputFocus] = useFocus()

    return (
        <> 
            <button onClick={setInputFocus} >
               FOCUS
            </button>
            <input ref={inputRef} />
        </>
    )

}

const useFocus = () => {
    const htmlElRef = useRef(null)
    const setFocus = () => {htmlElRef.current &&  htmlElRef.current.focus()}

    return [ htmlElRef, setFocus ] 
}

完整演示

React 16.3 +类组件-exploitFocus

class App extends Component {
  constructor(props){
    super(props)
    this.inputFocus = utilizeFocus()
  }

  render(){
    return (
      <> 
          <button onClick={this.inputFocus.setFocus}>
             FOCUS
          </button>
          <input ref={this.inputFocus.ref}/>
      </>
    )
  } 
}
const utilizeFocus = () => {
    const ref = React.createRef()
    const setFocus = () => {ref.current &&  ref.current.focus()}

    return {setFocus, ref} 
}

完整演示

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android