![](/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.