【问题标题】:React: prevent sorted table from re-rendering when a row is editedReact:防止在编辑行时重新呈现排序表
【发布时间】:2017-10-26 13:00:41
【问题描述】:

我在 React 中有一个表格,允许对行进行排序和编辑,我在主组件的构造函数中设置了该表格:

this.state = {
    rows: [
          {id: 1, name: 'John Doe', contacts: 'john.doe@gmail.com', rsvp: false, accepted: 0},
          {id: 2, name: 'Jane Doe', contacts: 'jane.doe@gmail.com', rsvp: false, accepted: 1},   
    ], 
    sortBy: {key: null, order: null}  
}

它允许排序(当用户点击表头时,它会将 sortBy 设置为实际值和顺序,然后通过 props 将其传递给 RowList 组件)

行是这样渲染的(它们也作为属性传递):

//RowList component


let computedRows = rows;    

if(sortBy.key && sortBy.order) {
   computedRows = orderBy(computedRows, [sortBy.key.toLowerCase()], [sortBy.order])
}
   computedRows = computedRows.map((row, index) => 
                     <Row key={index} row={row} index={index} handleChange={handleChange} /> 
                  )

因此,如果您将 ket 设置为 name 并 order 为 asc,则会导致

//key = 'name'
//order = 'asc'

Jane Doe (text input) · janedoe@gmail.com (text input)...
John Doe (text input)· johndoe@gmail.com (text input)...

Row 本身是一堆允许编辑状态信息的输入,例如如果您更改名称,它会将名称更新为 Zohn Doe in 将在状态下更新它并在用户仍在键入时切换行并重新渲染表格...

我尝试在shouldComponentUpdate() 中返回false。它可以防止行切换,但也不允许更改输入中的值。

如何保留编辑输入但不更改顺序的能力?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    如果你使用rowid 属性作为key,同时根据id 更新状态,React 不会卸载输入元素,即使在数组中你也可以继续输入重新排序。

    不过,这可能不是理想的用户体验,因此您还可以创建一个自定义输入组件来跟踪其自己的输入状态并仅在模糊时传播更改(即,当它失去焦点时):

    class DeferredInput extends Component {
      state = { value: this.props.value };
    
      componentWillReceiveProps({value}) {
        if (value !== this.state.value) {
          this.setState({value});
        }
      }
    
      handleChange = (event) => {
        this.setState({value: event.currentTarget.value});
      }
    
      handleBlur = () => {
        this.props.onBlur(this.state.value);
      }
    
      render() {
        return (
          <input type='text' value={this.state.value} onChange={this.handleChange} onBlur={this.handleBlur}/>
        );
      }
    }
    

    像这样使用它:&lt;DeferredInput value={..} onBlur={..}/&gt;

    【讨论】:

    • 谢谢,这是一个有价值的改进,尽管在模糊之后仍然会发生排序——我想防止这种情况
    猜你喜欢
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2023-03-11
    • 2020-05-16
    • 1970-01-01
    • 2011-12-25
    • 2020-11-04
    • 2018-07-22
    相关资源
    最近更新 更多