【问题标题】:Remove a specific table row on onClick event in React component在 React 组件中删除 onClick 事件上的特定表格行
【发布时间】:2016-11-04 05:28:24
【问题描述】:

我是 React 新手,在删除记录后如何操作 DOM 时遇到了困难。我有一些反应组件,但我关注的是删除我设置的 rails api 中的记录。我在 Ajax onclick 调用上可以删除记录,但不知道使用 React 删除特定行的最佳方法。

满是数据的表格

var ContactAll = React.createClass({
  getInitialState: function() {
    return {
      contacts: [] 
    }
  },
  componentDidMount: function() {
    $.ajax({
      dataType: "json",
      url: '/all-contacts',
      type: "GET",
      context: this,
      success: function(data, status, xhr) {
        this.setState({ contacts: data });
      }
    });
  },
  render: function(){
    if(this.state.contacts == 0) {
      return (
        <div>Loading</div>
      )
    } else {
      var contactComponents = this.state.contacts.map(function(contact, i) {
        var full_name = contact.first_name + ' ' + contact.last_name

        return  <tr key={i} className="contact">
                  <td>{ full_name}</td>
                  <td></td>
                  <td>{ contact.email_address }</td>
                  <td>{ contact.phone_number }</td>
                  <td>{ contact.company_name }</td>
                  <td><DeleteButton email={contact.email_address} /></td>
                </tr>;
      });
      return <div>
              <table>
                <tbody>
                <tr>
                  <th>Contact Name</th>
                  <th></th>
                  <th>Email Address</th>
                  <th>Phone Number</th>
                  <th>Company Name</th>
                </tr>

                {contactComponents};

                </tbody>
              </table>
             </div>
    }
  }
});

ContactAll 组件中的删除按钮

var DeleteButton = React.createClass({
  onClick: function() {
    var email = this.props.email;

    $.ajax({
      data: {email_address: email },
      url: '/delete-contact',
      dataType: 'html',
      type: "POST",
      success: function(data, status, xhr) {
        $('.delete-success').slideDown(400);
        setTimeout(function() { $(".delete-success").slideUp(400); }, 5000);
      }
    });
  },
  render: function(){
    return(
      <button onClick={() => { this.onClick(this.props.email) }}>Delete</button>
    )
  }
});

在单击相应行的删除按钮时删除被删除的特定行的最佳方法是什么?

谢谢!

【问题讨论】:

    标签: javascript ruby-on-rails reactjs


    【解决方案1】:

    创建一个删除函数,然后将数组的索引发送到该函数中,并使用 splice 删除该数组条目。将此 deleteRow 函数的引用传递给子组件并从那里调用它,如 this.props.deleteRow(this.props.index); 。查看完整代码

    喜欢

    deleteRow: function(index) {
        var contacts = [...this.state.contacts];
        contacts.splice(index, 1);
        this.setState({contacts});
      },
    

    var ContactAll = React.createClass({
      getInitialState: function() {
        return {
          contacts: [] 
        }
      },
      componentDidMount: function() {
        $.ajax({
          dataType: "json",
          url: '/all-contacts',
          type: "GET",
          context: this,
          success: function(data, status, xhr) {
            this.setState({ contacts: data });
          }
        });
      },
      deleteRow: function(index) {
        var contacts = [...this.state.contacts];
        contacts.splice(index, 1);
        this.setState({contacts});
      },
      render: function(){
        if(this.state.contacts == 0) {
          return (
            <div>Loading</div>
          )
        } else {
          var contactComponents = this.state.contacts.map(function(contact, i) {
            var full_name = contact.first_name + ' ' + contact.last_name
    
            return  <tr key={i} className="contact">
                      <td>{ full_name}</td>
                      <td></td>
                      <td>{ contact.email_address }</td>
                      <td>{ contact.phone_number }</td>
                      <td>{ contact.company_name }</td>
                      <td><DeleteButton onClick ={this.deleteRow.bind(this)} index={i} email={contact.email_address} /></td>
                    </tr>;
          }.bind(this));
          return <div>
                  <table>
                    <tbody>
                    <tr>
                      <th>Contact Name</th>
                      <th></th>
                      <th>Email Address</th>
                      <th>Phone Number</th>
                      <th>Company Name</th>
                    </tr>
    
                    {contactComponents};
    
                    </tbody>
                  </table>
                 </div>
        }
      }
    }); 
    var DeleteButton = React.createClass({
      onClick: function() {
        var email = this.props.email;
        this.props.deleteRow(this.props.index);
        $.ajax({
          data: {email_address: email },
          url: '/delete-contact',
          dataType: 'html',
          type: "POST",
          success: function(data, status, xhr) {
            $('.delete-success').slideDown(400);
            setTimeout(function() { $(".delete-success").slideUp(400); }, 5000);
          }
        });
      },
      render: function(){
        return(
          <button onClick={() => { this.onClick(this.props.email) }}>Delete</button>
        )
      }
    });

    【讨论】:

    • 你检查解决方案了吗。如果您有任何路线,请告诉我
    • 嗨,Shubham,谢谢。我在 DeleteButton 组件中遇到错误,“this.props.deleteRow”不是函数。可能是什么问题?
    • @luke 似乎绑定不正确,因此 deleteRow 无法作为函数传递给孩子。尝试在父级的地图组件中使用 bind(this)。我为它编辑了代码
    • 我设法弄明白了。我最终使用了那个=这个技巧。 deleteRow={ that.deleteRow.bind(that) }
    • 是的,这也与我的建议不同:)
    【解决方案2】:

    要删除或更新一个元素,我建议刷新页面,就像这个简单的代码:

    const handleDelete = async () => {
        try {
          await updateElement(currentDesign.uid, { is_public: !is_public })
          fetchAllDataToTable({})
        } catch (error) {
          setErrorMessage(
            'An error occurred while attempting to delete or update, please try again later'
          )
        }
      }
    

    fetchAllDataToTable 是您获取表的所有数据的地方

    const fetchAllDataToTable = async ({}) => {
    
        try {
          let { designs } = await fetchData(
            null,
            limit,
            lastElement, 
          )
    
          setList(designs)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多