2016-03-31 15 views
4

Tıklandığında, yeni Input bileşenini ekleyeceğiniz bir Add input düğmesinin olmasını isterim. Aşağıda, istediğim mantığı uygulamak için bir yol olduğunu düşündüğüm React.js kodu var, ancak maalesef işe yaramıyor. BendeDüğme tıklatmasında React bileşenini nasıl eklerim?

istisnadır: invariant.js:39 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {input}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `FieldMappingAddForm`.

Bu sorunu nasıl çözerim?

import React from 'react'; 
import ReactDOM from "react-dom"; 


class Input extends React.Component { 
    render() { 
     return (
      <input placeholder="Your input here" /> 
     ); 
    } 
} 


class Form extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = {inputList: []}; 
     this.onAddBtnClick = this.onAddBtnClick.bind(this); 
    } 

    onAddBtnClick(event) { 
     const inputList = this.state.inputList; 
     this.setState({ 
      inputList: inputList.concat(<Input key={inputList.length} />) 
     }); 
    } 

    render() { 
     return (
      <div> 
       <button onClick={this.onAddBtnClick}>Add input</button> 
       {this.state.inputList.map(function(input, index) { 
        return {input} 
       })} 
      </div> 
     ); 
    } 
} 


ReactDOM.render(
    <Form />, 
    document.getElementById("form") 
); 

cevap

7

{} çıkarın., Bu .map önlemek ve sadece {this.state.inputList} kullanmak bu durumda

{this.state.inputList.map(function(input, index) { 
    return input; 
})} 

Example

veya bu durumda daha iyi kullanmaya gerek yoktur,

Example

İlgili konular