use*_*631 2 javascript ecmascript-6 reactjs
React.js:单击按钮时添加/删除输入字段:
当用户单击"添加"时,我希望添加新的输入字段.
name属性正在针对每个输入进行更改,通过增加中间的数字:
document-0-document document-1-document
我收到以下错误:
"TypeError:这是未定义的var arr = this.state.documents;"
我知道是什么创建了错误,但我没有找到修复.
HTML代码.
<fieldset class="fieldset">
<input type="file" name="document-0-document">
<div class="more-documents">
<input type="file" name="document-1-document">
<button data-reactid=".0.1">Add</button>
</div>
</fieldset>
Run Code Online (Sandbox Code Playgroud)
主要组件代码:
class DocumentsFieldSet extends Component{
constructor(props){
super(props);
this.state = {documents:[]}
}
add(i) {
var arr = this.state.documents;
arr.push(i);
this.setState({documents: arr});
}
eachDocument () {
return <DocumentInput key={i}/>
}
render (){
return (
<div>
{this.state.documents.map(this.eachDocument)}
<button onClick={this.add.bind()}>Add</button>
</div>
)
}
}
ReactDOM.render(<DocumentsFieldSet/>, document.querySelector ('.more- documents'))
Run Code Online (Sandbox Code Playgroud)
组件代码
class DocumentInput extends Component {
render() {
return <input type="file" name="document-{i}-document" ref="" />;
}
}
export default DocumentInput;
Run Code Online (Sandbox Code Playgroud)
Ale*_* T. 11
你的例子中有几个错误
你需要绑定this的.add方法
你没有把this.state.documents数组索引
里面DocumentInput没有i变数
class DocumentInput extends React.Component {
render() {
return <input
type="file"
name={ `document-${ this.props.index }-document` }
/>;
}
}
class DocumentsFieldSet extends React.Component{
constructor(props){
super(props);
this.state = {
documents: []
}
this.add = this.add.bind(this);
}
add() {
const documents = this.state.documents.concat(DocumentInput);
this.setState({ documents });
}
render () {
const documents = this.state.documents.map((Element, index) => {
return <Element key={ index } index={ index } />
});
return <div>
<button onClick={ this.add }>Add</button>
<div className="inputs">
{ documents }
</div>
</div>
}
}
ReactDOM.render(
<DocumentsFieldSet />,
document.getElementById('container')
);Run Code Online (Sandbox Code Playgroud)
.inputs {
margin: 5px 0;
padding: 10px;
border: 2px solid #000;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>Run Code Online (Sandbox Code Playgroud)