Javascript 如何在单击按钮时添加反应组件?
我希望有一个Javascript 如何在单击按钮时添加反应组件?,javascript,reactjs,Javascript,Reactjs,我希望有一个addinput按钮,当单击该按钮时,将添加一个新的input组件。下面是React.js代码,我认为这是实现我想要的逻辑的一种方法,但不幸的是它不起作用 我得到的例外是: invariant.js:39未捕获的不变冲突:对象无效 React子对象(找到:具有键{input}的对象)。如果你想 渲染子对象的集合,改用数组或换行 使用React加载项中的createFragment(对象)创建对象。检查 FieldMappingAddForm的渲染方法 我如何解决这个问题 import
addinput
按钮,当单击该按钮时,将添加一个新的input
组件。下面是React.js代码,我认为这是实现我想要的逻辑的一种方法,但不幸的是它不起作用
我得到的例外是:
invariant.js:39未捕获的不变冲突:对象无效
React子对象(找到:具有键{input}的对象)。如果你想
渲染子对象的集合,改用数组或换行
使用React加载项中的createFragment(对象)创建对象。检查
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”导入React;
从“react dom”导入react dom;
类输入扩展了React.Component{
render(){
返回(
);
}
}
类形式扩展了React.Component{
建造师(道具){
超级(道具);
this.state={inputList:[]};
this.onAddBtnClick=this.onAddBtnClick.bind(this);
}
onAddBtnClick(事件){
const inputList=this.state.inputList;
这是我的国家({
inputList:inputList.concat()
});
}
render(){
返回(
添加输入
{this.state.inputList.map(函数(输入,索引){
返回{input}
})}
);
}
}
ReactDOM.render(
,
document.getElementById(“表单”)
);
删除{}
,在这种情况下不需要使用它
{this.state.inputList.map(function(input, index) {
return input;
})}
在这种情况下,最好避免使用.map
,只使用{this.state.inputList}
反应钩子版本
import React,{useState}来自“React”;
从“react dom”导入react dom;
常量输入=()=>{
返回;
};
常数形式=()=>{
常量[inputList,setInputList]=useState([]);
const onAddBtnClick=事件=>{
setInputList(inputList.concat());
};
返回(
添加输入
{inputList}
);
};
ReactDOM.render(,document.getElementById(“表单”);
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"));