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

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

最佳答案

React Hook 版本

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

关于javascript - 如何在单击按钮时添加 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36336411/

相关文章:

javascript - 如何添加/更改属性的值

javascript - .then() 在 promise 解决之前触发

javascript - 如何防止 JQuery 动画调用排队?

javascript - 无法从 iframe 访问浏览器平板电脑(Firefox 除外)中的父级 javascript

javascript - React - 如何实现页面范围的操作?

html - 文本重叠视频标签 CSS

reactjs - 如何在 react 中将 react 钩子(Hook)对象从 index.js 传递到 axios 拦截器

javascript - 初学者使用chart.js : having trouble display state full of data into a column chart using variables

javascript - React 组件不刷新或重新渲染

javascript - Next.js : Refresh page after modifying a file, 无需重新运行 'npm run'