所以我开始接触 React,但我似乎无法解决这个简单的问题(可能是因为 sleep 不足)
我想在单击“添加行”时在 render
中动态添加元素(或 div)。
我该如何继续呢?我是否需要将其保存在数组中并在渲染函数中,我必须映射它?
class SimpleExample extends React.Component {
constructor(props) {
super(props)
this.handleAddingDivs = this.handleAddingDivs.bind(this)
}
handleAddingDivs() {
const uniqueID = Date.now()
return (
<div>
This is added div! uniqueID: {uniqueID}
</div>
)
}
render() {
return (
<div>
<h1>These are added divs </h1>
<button className="btn-anchor-style add-row-link" type="button" onClick={this.handleAddingDivs}>{'Add Row'}</button>
</div>
)
}
}
最佳答案
假设您想要添加多个 div,因此为此维护一个状态变量、计数或任何其他数据(您也可以使用任何数组
并存储所有 div 的唯一值),然后使用 map 或任何其他循环为此创建 div。
检查这个工作片段:
class SimpleExample extends React.Component {
constructor(props) {
super(props);
this.state = {count : 0}
this.handleAddingDivs = this.handleAddingDivs.bind(this)
}
handleAddingDivs() {
this.setState({count: this.state.count + 1})
}
renderDivs(){
let count = this.state.count, uiItems = [];
while(count--)
uiItems.push(
<div>
This is added div! uniqueID: {count}
</div>
)
return uiItems;
}
render() {
return (
<div>
<h1>These are added divs </h1>
<button className="btn-anchor-style add-row-link" type="button" onClick={this.handleAddingDivs}>{'Add Row'}</button>
{this.renderDivs()}
</div>
)
}
}
ReactDOM.render(<SimpleExample/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id ='app'/>
关于javascript - React.js - 动态添加 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44015876/