mh-rn-component
Version:
122 lines (104 loc) • 3.06 kB
JavaScript
import React, { useRef, useEffect, useState } from 'react';
import { View, Text, FlatList } from "react-native";
import { randomBaseId } from "../helpers";
const Columns = _ref => {
let {
data,
columnHeight,
defaultIndex = 0,
visibleItemCount,
columnIndex,
onChange,
customFieldName,
...rest
} = _ref;
const customFieldNameValue = customFieldName.value || "value";
const columnRef = useRef(null);
const [curIndex, setCurIndex] = useState(defaultIndex);
const renderColumnItems = (item, index) => {
const type = typeof item;
return /*#__PURE__*/React.createElement(View, {
style: {
height: columnHeight,
justifyContent: "center"
}
}, /*#__PURE__*/React.createElement(Text, {
style: {
color: index === curIndex ? "#333" : "#ccc",
textAlign: "center"
}
}, type === 'number' || type === 'string' ? item : item[customFieldNameValue]));
};
const renderColumns = _ref2 => {
let {
item,
index
} = _ref2;
return /*#__PURE__*/React.createElement(View, {
style: {
flex: 1
}
}, renderColumnItems(item, index));
}; // 占位
const vacancy = () => {
const multiple = (visibleItemCount - 1) / 2;
return /*#__PURE__*/React.createElement(View, {
style: {
height: columnHeight * multiple
}
});
};
const move = index => {
var _columnRef$current;
(_columnRef$current = columnRef.current) === null || _columnRef$current === void 0 ? void 0 : _columnRef$current.scrollToIndex({
viewPosition: 0,
index: Number(index)
});
};
useEffect(() => {
rest.cascadeLevel && setCurIndex(0);
}, [data]);
useEffect(() => {
move(curIndex); //!传数组对象和传数组的区别
onChange(data[curIndex][customFieldNameValue] || data[curIndex], curIndex, columnIndex);
}, [curIndex]);
const onScrollEnd = _ref3 => {
let {
nativeEvent
} = _ref3;
let _index = Number((Number(nativeEvent.contentOffset.y) / columnHeight).toFixed(0));
if (data.length < _index) {
_index = data.length - 1;
} else if (_index < 0) {
_index = 0;
}
if (data.length > _index && _index >= 0) {
// 节流 只有变化的时候才会调用
if (Math.abs(_index) !== curIndex) {
setCurIndex(Math.abs(_index));
}
}
}; // 自定义key值
const _baseId = randomBaseId();
const customKey = (item, index) => {
return `${_baseId}${index}`;
};
return /*#__PURE__*/React.createElement(FlatList, {
showsHorizontalScrollIndicator: false,
showsVerticalScrollIndicator: false,
ref: columnRef,
data: data,
renderItem: renderColumns,
ListHeaderComponent: vacancy,
ListFooterComponent: vacancy,
keyExtractor: customKey,
getItemLayout: (data, index) => ({
length: columnHeight,
offset: columnHeight * index,
index
}),
onScrollEndDrag: onScrollEnd
});
};
export default Columns;
//# sourceMappingURL=Columns.js.map