我知道这是发生的,因为React正在重新渲染页面,因此输入字段失去了焦点。我已经尝试了所有我能想到的东西,但是没有一个起作用!我找不到解决此问题的方法。 这是我的React代码。
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:我是React的新手。任何帮助将不胜感激。
注意:键入一些随机单词以抑制StackOverflow警告-“看起来您的问题主要是代码,等等”。
答案 0 :(得分:0)
我将<Root>...</Root>
更改为<div>...</div>
,并且现在它可以正常工作了。奇怪!