简体   繁体   中英

Input field looses focus in React

I know that it is happening because React is re-rendering the page and hence the input field is losing the focus. I have tried everything I could think of but none worked! I can't find a way to resolve the issue. Here's my React code.

import React, { ChangeEvent, Component, ReactNode } from 'react'
import { Root, /*Routes*/ } from 'react-static'
import { Link } from '@reach/router'
import { Helmet } from 'react-helmet'
import './app.css'
// import FancyDiv from '@components/FancyDiv'

/* According to the following documentation,
 * https://github.com/nozzle/react-static/blob/master/docs/concepts.md#writing-universal-node-safe-code
 */
let Sidenav = { init(_: any, options: any) { return {_, options} } }
let updateTextFields = () => {}
if (typeof window !== 'undefined') {
  const materialize = require('materialize-css')
  Sidenav = materialize.Sidenav
  updateTextFields = () => materialize.updateTextFields()
}

interface IComponentProps {

}

interface IComponentState {
  'long_url': string
}

const LongUrlInput = (props: any) =>
  <input
    key='in1'
    id="long_url"
    type="text"
    className="validate"
    onChange={ props.handleLongUrl }
  />

export default class App extends Component<IComponentProps, IComponentState> {
  constructor(props: any) {
    super(props)
    this.state = {
      'long_url': ''
    }
  }

  componentDidMount(): void {
    const elem = document.querySelectorAll('.sidenav')
    Sidenav.init(elem, {})
    updateTextFields()
  }

  handleLongUrl = (event: ChangeEvent<HTMLInputElement>): void => {
    console.log('types', event.target.value, this.state.long_url)
    this.setState({
      'long_url': event.target.value
    })
  }

  render(): ReactNode {
    return (
      <Root>

        <Helmet>
          <title>ShortURI - URL Shortener</title>
          <meta name="description" content="Create short URLs and also monitor traffic with proper analysis report." />
        </Helmet>

        <nav className={'indigo'}>
          <div className="nav-wrapper" style={{ padding: '0 20px' }}>
            <Link to={'/'} className={'brand-logo'}>ShortURI</Link>
            <a href={''} data-target="slide-out" className="sidenav-trigger">
              <i className="material-icons">menu</i>
            </a>
            <ul id="nav-mobile" className="right hide-on-med-and-down">
              <li><Link to={'/about'}>About</Link></li>
              <li><Link to={'/#!'}>Login</Link></li>
              <li><Link to={'/#!'}>Register</Link></li>
            </ul>
          </div>
        </nav>
        <ul id="slide-out" className="sidenav">
          <li><a className="sidenav-close" href="#">Clicking this will close Sidenav</a></li>
        </ul>

        <div className="content">
          <div className="row">
            <div className="card">
              <div className="card-content black-text">
                <span className="card-title">Card Title</span>
                <div className="input-field col s6">
                  <LongUrlInput handleLongUrl={this.handleLongUrl}/>
                  <label className="active" htmlFor="long_url">Long URL</label>
                </div>
              </div>
            </div>
          </div>
          {/*<FancyDiv>*/}
            {/*<Routes/>*/}
          {/*</FancyDiv>*/}
        </div>
      </Root>
    )
  }
}

PS: I am new to React. Any help would be appreciated.

Note: Typing some random words to suppress StackOverflow Warning - "Looks like your question is mostly code, blah-blah".

I changed <Root>...</Root> to <div>...</div> and somehow it is now working. Weird!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM