React.js - 动态添加 div 元素

3

我正在学习React,但是由于缺乏睡眠,似乎无法解决这个简单的问题。

我想在单击“添加行”时,在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? - undefined
多个div,只要我按下添加行按钮 - undefined
1
你猜对了,使用数组的 map 方法是一个不错的方式。确保将数据保存在状态中,这样可以自动重新渲染。 - undefined
4个回答

3

假设您想要添加多个

,因此需要维护一个状态变量,例如计数器或其他数据(也可以使用任何array并存储所有
的唯一值),然后使用map或其他循环来创建这些

请查看以下工作示例:

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'/>


太棒了,这个解决了问题,而且这段代码运行得非常出色。非常感谢! - undefined

1

尝试下面的代码。每当您点击按钮时,都会生成并存储一个唯一的ID在state.uids中。在render()中,根据state.uids呈现添加的divs。

class SimpleExample extends React.Component {
    constructor(props) {
        super(props)
        this.handleAddingDivs = this.handleAddingDivs.bind(this)
        this.state = {uids:[]}
    }


    handleAddingDivs() {
        let curr = this.state.uids;
        const uniqueID = Date.now()
        this.setState({uids:[...curr, uniqueID]});
    }

    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.state.uids.map((uid, idx)=>
                  <div key={uid}>This is added div! uniqueID: {uid}</div>
                )}
            </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'/>


1

是的,您需要将有关新

的数据存储在某个地方...

这就是Flux / Redux有时用于的地方:您将需要呈现的所有数据存储在Store中,然后您就知道要呈现什么。

但是,如果您只想使用React,则使用state!在您的情况下,您的状态应该像这样:

{
  addedDivs: [
    {uniqueId: 123},
    {uniqueId: 754},
  ]
}

然后在渲染时,您将对其进行映射(不要忘记添加key

this.state.addedDivs.map((item) = > {return (<div key={item.uniqueId}></div>) })

当你需要添加一些onClick事件时,你只需要使用setState:

this.setState((prevState, props) => {
  var addedDivs = prevState.addedDivs;
  var uniqueId = Date.now();
  addedDivs.push({uniqueId: uniqueId});
  return {addedDivs: addedDivs}
});

1
你在考虑DOM操作/jQuery方面的术语。当你使用React时,你需要从数据的角度思考,以及它如何与你的DOM相关联。
在你的情况下,你需要:
  • 每次点击“添加行”按钮时,在handleAddingDivs()方法中使用一个新的行更新你的组件状态
  • 基于状态渲染行,在render()方法中


class SimpleExample extends React.Component {
  constructor(props) {
    super(props)
    this.handleAddingDivs = this.handleAddingDivs.bind(this)
   }

  //Modify state of component when 'Add Row' button is clicked
  handleAddingDivs() {
    const uniqueID = Date.now();
    this.setState({rows: this.state.rows.concat(uniqueId)});
  }

  //The `render()` function will be executed everytime state changes
  render() {
    return (
      <div>
        <h1>These are added divs </h1>
        //The rows are rendered based on the state
        {this.state.rows.map(function(uniqueId) {
          return ( 
            <div key={item.uniqueId}>This is added div! uniqueID: {uniqueID}</div>
          )
        }}
        <button className="btn-anchor-style add-row-link" type="button" onClick={this.handleAddingDivs}>{'Add Row'}</button>                  
      </div>
    )
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接