![](/img/trans.png)
[英]How do I add React component on button click in Data Grid Material-UI?
[英]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"));
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.