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

新手上路,请多包涵

我想要一个 Add input 按钮,单击该按钮将添加一个新的 Input 组件。以下是我认为是实现我想要的逻辑的一种方法的 React.js 代码,但不幸的是它不起作用。

我得到的例外是:

invariant.js:39 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {input}).如果您打算渲染子集合,请改用数组或使用 React 附加组件中的 createFragment(object) 包装对象。检查 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")
);

原文由 hans-t 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 284
2 个回答

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

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

Example

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

Example

原文由 Oleksandr T. 发布,翻译遵循 CC BY-SA 3.0 许可协议

反应挂钩版本

单击此处查看实时示例

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

原文由 Jonathan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题