我希望按键后保持对“输入”元素的关注
代码:
import React, { Component } from 'react'
class App extends Component {
render() {
return (
<NewContactBox/>
)
}
}
class NewContactBox extends Component {
constructor(props) {
super(props)
this.state = {
name: '',
email: '',
phone: '',
}
this.fieldRefs = {
name: React.createRef(),
email: React.createRef(),
phone: React.createRef(),
}
}
hc = (ev, type, ref) => {
this.setState({
[type]: ev.target.value
})
// console.log(ref)
ref.focus()
}
render() {
const ContactInput = ({fields}) => (
fields.map((f) => (
<input
key={f.id}
className={`p-1 my-3 w-100 mr-3 ${f.id}`}
size="16px"
placeholder={f.placeholder}
value={this.state[f.id]}
ref={this.fieldRefs[f.id]}
onChange={(e) => this.hc(e, f.id, this.fieldRefs[f.id].current)}
/>
))
)
return (
<ContactInput
fields={[
{ placeholder: "Name", id: 'name' },
{ placeholder: "Phone number", id: 'phone' },
{ placeholder: "Email", id: 'email' },
]}
/>
)
}
}
export default App
我尝试过
Change01
-以另一种方式在Input标记内声明引用
Change02
-不将引用显式传递给onChange,然后直接从this.fieldrefs
constructor(props) {
this.fieldRefs = {} // Change01
}
hc = (ev, type) => { //Change02
this.setState({
[type]: ev.target.value
})
// console.log(this.fieldRefs[type].current)
this.fieldRefs[type].current.focus()
}
...
<input
...
ref={(el) => this.fieldRefs[f.id] = el} //Change01
onChange={(e) => this.hc(e, f.id)} //Change02
/>
但这没有帮助,每次按键后,body元素变为活动元素。
答案 0 :(得分:0)
也许您需要将ContactInput
声明移到render()
之外,否则每次重新发布时都会重新创建一个新组件。例如,
render() {
return (
<this.ContactInput
fields={[
{ placeholder: "Name", id: 'name' },
{ placeholder: "Phone number", id: 'phone' },
{ placeholder: "Email", id: 'email' },
]}
/>
)
}
ContactInput = ({fields}) => (
// If react complains about returning multiple component, add this React.Fragment short syntax
<React.Fragment>
{fields.map((f) => (
<input
key={f.id}
className={`p-1 my-3 w-100 mr-3 ${f.id}`}
size="16px"
placeholder={f.placeholder}
value={this.state[f.id]}
ref={this.fieldRefs[f.id]}
onChange={(e) => this.hc(e, f.id, this.fieldRefs[f.id].current)}
/>
))}
<React.Fragment/>
)