我想要一个 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) 包装对象。检查
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")
);
原文由 hans-t 发布,翻译遵循 CC BY-SA 4.0 许可协议
删除
{}
., 在这种情况下没有必要使用它Example
或者在这种情况下更好地避免
.map
并且只使用{this.state.inputList}
,Example