Forráskód Böngészése

Focus inputs when they mount

Fela Maslen 7 éve
szülő
commit
0c99ffd3cc
1 módosított fájl, 30 hozzáadás és 16 törlés
  1. 30 16
      src/components/Field/index.js

+ 30 - 16
src/components/Field/index.js

@@ -1,25 +1,39 @@
-import React from 'react';
+import React, { Component } from 'react';
 import PropTypes from 'prop-types';
 
-export default function Field({ type, ...props }) {
-    if (type === 'number') {
-        return (
-            <input type="number" {...props} />
-        );
+export default class Field extends Component {
+    static propTypes = {
+        type: PropTypes.string.isRequired
+    };
+
+    constructor(props) {
+        super(props);
+
+        this.input = React.createRef();
+    }
+
+    componentDidMount() {
+        this.input.current.focus();
     }
 
-    if (type === 'textarea') {
+    render() {
+        const { type, ...props } = this.props;
+
+        if (type === 'number') {
+            return (
+                <input ref={this.input} type="number" {...props} />
+            );
+        }
+
+        if (type === 'textarea') {
+            return (
+                <textarea ref={this.input} {...props} />
+            );
+        }
+
         return (
-            <textarea {...props} />
+            <input ref={this.input} type="text" {...props} />
         );
     }
-
-    return (
-        <input type="text" {...props} />
-    );
 }
 
-Field.propTypes = {
-    type: PropTypes.string.isRequired
-};
-