我正在使用react-sortable-hoc库对项目列表进行排序。不仅仅是列出我需要在单击单个项目时运行功能。
列表和排序,一切正常。当我点击通过clickFunction()
列出的名称时,如何传递应该被称为SortableItem
的道具来控制名称?
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-hoc';
const SortableItem = SortableElement(({value}) => <li>{value.first_name}</li>);
const SortableList = SortableContainer(({items}) => {
return (
<ul>
{items.map((value, index) => (
<SortableItem key={`item-${index}`} index={index} value={value} />
))}
</ul>
);
});
class Details extends React.Component {
clickFunction(name) {
console.log(name)
}
onSortEnd({oldIndex, newIndex}) {
this.setState({
testlist: arrayMove(this.state.testlist, oldIndex, newIndex),
});
};
render() {
return (
<div>
<SortableList items={this.state.testlist} onSortEnd={this.onSortEnd.bind(this)} pressDelay="200" />
</div>
)
}
}
答案 0 :(得分:2)
您可以从Details组件传递函数,并在SortableList和SortableItem的props中接收它,如
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-hoc';
const SortableItem = SortableElement(({value, clickFunction}) => <li onClick={() => clickFunction(value)}>{value.first_name}</li>);
const SortableList = SortableContainer(({items, clickFunction}) => {
return (
<ul>
{items.map((value, index) => (
<SortableItem key={`item-${index}`} index={index} clickFunction={clickFunction} value={value} />
))}
</ul>
);
});
class Details extends React.Component {
clickFunction(name) {
console.log(name)
}
onSortEnd({oldIndex, newIndex}) {
this.setState({
testlist: arrayMove(this.state.testlist, oldIndex, newIndex),
});
};
render() {
return (
<div>
<SortableList items={this.state.testlist} onSortEnd={this.onSortEnd.bind(this)} pressDelay="200" clickFunction={this.clickFunction} />
</div>
)
}
}
答案 1 :(得分:0)
这是将道具传递给SortableContainer的示例:
const SortableList = SortableContainer(({items, props, handleClickFunction, fieldSelector}) => {
const subComponentList = [];
items.map((value, index) =>
subComponentList.push(
<SortableItem
key={`item-${index}`}
index={index}
value={value}
props={props}
handleClickFunction={handleClickFunction}
fieldSelector={fieldSelector}
/>)
);
return (
<ul>{subComponentList}</ul>
);
});