在我的情況下,我想開發一個可排序的表單列表。不幸的是,表單狀態在排序後沒有更新。請幫忙。我堅持了一個星期。對formData的反應可分類的特別
我很抱歉,我不知道如何將'react-sortable-hoc'庫導入到後面的JSFiddle中。
鏈接:https://github.com/clauderic/react-sortable-hoc
import React, {Component} from 'react';
import {render} from 'react-dom';
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-hoc';
class ElementItem extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.value
}
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<input type="text" name="value" value={this.state.value} onChange={this.handleInputChange}/>
)
}
}
const SortableItem = SortableElement(({value}) =>
<li><ElementItem value={value}/></li>
);
const SortableList = SortableContainer(({items}) => {
return (
<ul>
{items.map((value, index) => (
var key = 'item-' + index;
<SortableItem key={key} index={index} value={value} />
))}
</ul>
);
});
export default class SortableComponent extends React.Component {
\t constructor(props) {
super(props);
this.state = {
items: Array.apply(null, Array(100)).map((val, index) => 'Item ' + index)
}
}
onSortEnd({oldIndex, newIndex}) {
this.setState({
items: arrayMove(this.state.items, oldIndex, newIndex)
});
}
render() {
return (
<SortableList items={this.state.items} onSortEnd={this.onSortEnd.bind(this)} helperClass="SortableHelper" />
)
}
}
render(<SortableComponent/>, document.getElementById('root'));
<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>
<script src="https://npmcdn.com/react-sortable-hoc/dist/umd/react-sortable-hoc.min.js"></script>
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
感謝Evgeny Sorokin。請讓我試試看。 –
我不知道爲什麼。我需要在ElementItem上添加ComponentWillReceiveProps()和componentWillUpdate()以更新父狀態和子道具以實現此目的。但是很麻煩,還有其他解決方案嗎? –