javascript - 如何将焦点设置为在循环中动态创建的渲染 redux 表单

标签 javascript reactjs redux react-redux redux-form

我正在使用 Redux-form,我需要在单击按钮时渲染时将焦点设置在文本框上,我已经使用了 autoFocus 但它会在循环的第二个索引上工作

also i have used document.getElementById('idname) as well

我的代码:

constructor(props){
        super(props)
        this.inputFocus = this.utilizeFocus()
    }
const utilizeFocus = () => {
    const ref = React.createRef()
    const setFocus = () => {ref.current &&  ref.current.focus()}

    return {setFocus, ref} 
}
componentDidUpdate(){
        const set = this.inputFocus.ref.current;
        const sett = ReactDOM.findDOMNode(set);
        if(sett){
            sett.focus();
        }
    } 
<Field
   name={`${facility}.facilityRef`}
    component='input'
    type='text'
    ref={this.inputFocus}
    autoFocus
    aria-label="Facility Ref"
    />

It works fine, I will get the focus on the particular field but it won't go to next field, Means every rendering focus comes into the same textbox. which life cycle I need to use for this.

我已经集成了 componentDidMount 但它不会有帮助

I have also try refs functionality while searching from StackOverflow but every where showing for button click But my question is for dynamically created form then apply focus

If you add autofocus, You won't need to write any above code, I am using this code only for index 0 but on first rendering it is showing perfect but we cannot go to the other text box

最佳答案

这将帮助您自动聚焦到新创建的字段中。本质上,您希望动态创建引用,以便输入具有唯一引用。然后在 componentDidUpdate() 中简单地定位该 ref 并使用 .focus()

请注意,这没有 Redux-Form,但您可能会创建相同的逻辑。 :)

参见代码和框:https://codesandbox.io/s/cranky-cookies-mz8gx

工作代码:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fields: []
    };
    this.nodes = new Map();
  }

  addField = () => {
    const { fields } = this.state;
    let newFieldObj = {
      id: fields.length,
      value: ""
    };

    this.setState({
      fields: [...fields, newFieldObj]
    });
  };

  componentDidUpdate(prevProps, prevState) {
    if (prevState.fields.length !== this.state.fields.length) {
      const refs = Array.from(this.nodes.values());
      const newestRef = refs[refs.length - 1];
      newestRef.focus();
    }
  }

  handleOnChange = (e, inputId) => {
    const fieldsCopy = [...this.state.fields];

    const fieldToUpdate = fieldsCopy.find(field => field.id == inputId);

    fieldToUpdate.value = e.target.value;

    this.setState({
      fields: fieldsCopy
    });
  };

  renderFields = () => {
    const { fields } = this.state;
    return fields.map(field => {
      return (
        <div>
          <input
            key={field.id}
            ref={ref => this.nodes.set(field.id, ref)}
            value={field.value}
            onChange={e => this.handleOnChange(e, field.id)}
          />
        </div>
      );
    });
  };

  render() {
    return (
      <div>
        <div>{this.renderFields()}</div>
        <button onClick={this.addField}>Add Field</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

关于javascript - 如何将焦点设置为在循环中动态创建的渲染 redux 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57622645/

相关文章:

reactjs - Typescript 找不到导入类型 Action

javascript - 如何在 Chrome 中试用 SIMD 指令?

javascript - Ember.js:在服务的 Handlebars 中使用计算属性

reactjs - PrimeReact 结合 react 图标

reactjs - 清除浏览器数据后无法在 Object.extractRehydrationInfo 读取未定义的属性(读取 [api.reducerPath])

react-native - React Native redux saga 产量不适用于第一个操作

javascript - 我可以在 sendgrid 上使用 Javascript 吗?

javascript - 调试javascript的正确方法是什么?

javascript - 如果我有一个按钮触发 React 中第二个子组件的状态,如何将状态传递给父组件

reactjs - SEO 友好的 React-Redux 应用程序