簡體   English   中英

如何在單擊按鈕時添加 React 組件?

[英]How do I add React component on button click?

我想要一個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) 包裝 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")
);

反應鈎子版本

單擊此處查看實時示例

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

刪除{} .,在這種情況下沒有必要使用它

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

Example

或者在這種情況下最好避免.map並只使用{this.state.inputList}

Example

const [visible,setVisible] = useState(false);
return(
    <>
    <button onClick={()=>setVisible(true)}>Hit me to add new div</button>
    {
      visible ? (
        <div id='addThisContainer'>
          {/* Your code inside */}
        </div>
       ) : null
    }
  </>
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM