如何在按钮单击时添加React组件?

时间:2016-03-31 14:33:42

标签: javascript reactjs

我希望有Add input按钮,点击后会添加新的Input组件。以下是React.js代码,我认为这是实现我想要的逻辑的一种方式,但不幸的是它不起作用。

我得到的例外是: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`.

如何解决这个问题?

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")
);

2 个答案:

答案 0 :(得分:7)

删除{}。,在这种情况下不必使用它

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

Example

或更好在这种情况下避免使用.map并使用{this.state.inputList}

Example

答案 1 :(得分:4)

反应钩版本

Click here for live example

import React, { useState } from "react";
import ReactDOM from "react-dom";

const Input = () => {
  return <input placeholder="Your input here" />;
};

const Form = () => {
  const [inputList, setInputList] = useState([]);

  const onAddBtnClick = event => {
    setInputList(inputList.concat(<Input key={inputList.length} />));
  };

  return (
    <div>
      <button onClick={onAddBtnClick}>Add input</button>
      {inputList}
    </div>
  );
};

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