我希望有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")
);
答案 0 :(得分:7)
删除{}
。,在这种情况下不必使用它
{this.state.inputList.map(function(input, index) {
return input;
})}
或更好在这种情况下避免使用.map
并使用{this.state.inputList}
,
答案 1 :(得分:4)
反应钩版本
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"));