如何在 ReactJS 中添加元素?如果我想在 按钮点击 时添加一个 表格行,使用 appendChild()
是不是一种不好的做法?
如何在 ReactJS 中添加元素?如果我想在 按钮点击 时添加一个 表格行,使用 appendChild()
是不是一种不好的做法?
使用appendChild()方法是不好的做法
是的,这违背了ReactJS的整个目的。
你的ReactJS应用程序应该基于数据渲染UI,在这种情况下,您永远不需要使用直接的DOM操作,特别是因为您所做的任何更改都将在下一个ReactJS渲染时被清除。
ReactJS的工作方式是创建虚拟DOM,并将更改与先前版本的虚拟DOM进行比较。如果存在更改,则会更新用户看到的真实DOM。这就是为什么你不应该使用像appendChild
和innerHTML
这样的函数或其他DOM操作方法,因为ReactJS不关心您在真实DOM中手动执行的操作,并且会将其清除。
以下是一个基本的可运行示例,其中包含两个人的表格和一个添加另一个人到状态的按钮,这会导致表格重新呈现并添加另一个tr
。
class App extends React.Component {
constructor(props){
super(props);
this.state = {
tableData: [
{ name: 'John', age: 25 },
{ name: 'Peter', age: 43 }
]
};
this.renderTableRows = this.renderTableRows.bind(this)
this.addPerson = this.addPerson.bind(this)
}
addPerson() {
const newPerson = { name: 'Mary', age: 38 }
const tableData = [
...this.state.tableData,
newPerson
]
this.setState({tableData});
}
renderTableRows() {
const { tableData } = this.state
if (!tableData) return null;
let result = [];
tableData.forEach(person => {
result.push(
<tr>
<td>{person.name}</td>
<td>{person.age}</td>
</tr>
)
});
return result;
}
render() {
return (
<div>
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
{this.renderTableRows()}
</table>
<button onClick={this.addPerson}>Add Person</button>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
table, th, td {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
https://reactjs.org/docs/faq-internals.html
https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model
......
this.state = {
ArrayData: [],
newRowValueObject: {}
}
....
<Button onClick={()=>[...this.state.ArrayData, newRowValueObject]}> <Button/>