【发布时间】:2018-05-07 15:29:20
【问题描述】:
我有一个动态生成的输入列表。
input --> onClick new Input beneath
[dynamically added]input
input
如何才能给这个动态添加的输入焦点?
输入具有 textInput ref。这部分有效:
componentWillUpdate(){
this.textInput.focus();
}
然而,只是工作或第一个新的输入。然后似乎逻辑中断了。
输入是来自数组的 .map()。有没有办法说,如果当前渲染的元素有 el.isActive 来聚焦它。或者只是说用索引 5 聚焦输入?
代码
输入生成文件/组件
import React from 'react';
import ReactDOM from 'react';
import _ from 'lodash'
class SeveralInputs extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ' '
}
this.showIndex = this
.showIndex
.bind(this)
this.map = this
.map
.bind(this)
this.handleChange = this
.handleChange
.bind(this);
}
componentWillUpdate() {
this.textinput && this
.textInput
.focus();
}
render() {
return (
<ul>
{this.map()}
</ul>
)
}
map() {
{
return this
.props
.data
.map((name, index) => <li
onKeyPress={this
.showIndex
.bind(this, index)}
key={index}><input
onChange={this
.handleChange
.bind(this, index)}
task={this.task}
value={name.value}
ref={(input) => {
this.textInput = input;
}}
type="text"/>{name.value}</li>)
}
}
handleChange(index, e) {
let data = this
.props
.data
.splice(index, 1, {
value: e.target.value,
isActive: true
})
this
.props
.refreshState(data);
}
showIndex(index, e) {
if (e.which === 13 || e.keyPress === 13) {
let data = this.props.data[index].isActive = false
data = this
.props
.data
.splice(index + 1, 0, {
value: ' ',
isActive: true
})
this
.props
.refreshState(data);
} else {
return null
}
}
}
export default SeveralInputs
存在于父组件中的数据
const data = [
{
value: 0,
isActive: true
}, {
value: 2,
isActive: false
}
]
父母声明:
this.state = { 错误:空, 数据 };
父母渲染
render() {
return (
<div>
{/* <Input/> */}
{/* <SeveralItems refreshState={this.refreshState} data={this.state.data.value}/> */}
<SeveralInputs refreshState={this.refreshState} data={this.state.data}/> {/* <SeveralInputsNested refreshState={this.refreshState} data={this.state.data}/> {this.items()} */}
</div>
);
}
refreshState(data) {
this.setState({data: this.state.data})
console.log(this.state.data)
}
【问题讨论】:
标签: javascript reactjs