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

han*_*s-t 6 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")
);
Run Code Online (Sandbox Code Playgroud)

小智 12

React Hook 版本

点击这里查看现场示例

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"));
Run Code Online (Sandbox Code Playgroud)


Ale*_* T. 10

删除{}.,在这种情况下没有必要使用它

{this.state.inputList.map(function(input, index) {
  return input;
})}
Run Code Online (Sandbox Code Playgroud)

Example

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

Example