从数组中删除项目仅适用于最后渲染的项目,但所选项目已从列表中删除
const [otherPhones, setOtherPhones] = useState([]);
{otherPhones.map((item, i) => {
return (
<View
style={{
...DefaultStyles.iconContainer,
marginBottom: hp("1.25%")
}}
key={i}
>
<PhoneNumberPicker
placeholder={i18n.t("other_phone")}
style={{ flex: 10 }}
countryHint={countryHint}
onChange={value => {
_handleOtherPhone(value, i);
}}
/>
<IconButton
style={{ flex: 1 }}
icon="trash-can-outline"
color={SECONDARY}
size={SCALE_20}
onPress={_deleteOtherPhone.bind(this, i)}
/>
</View>
);
})}
const _deleteOtherPhone = index => {
const temp = [...otherPhones];
temp.splice(index, 1);
setOtherPhones(temp);
};
当我删除PhoneNumberPicker并仅显示简单的属性项时,一切正常。 PhoneNumberPicker是带有一些附加组件的TextInput。
答案 0 :(得分:0)
也许这将对某人有所帮助,我使用useRef()反应钩子来引用DOM上每个呈现的Child,然后在删除项目后使用新索引更新它们(在删除所选元素之后)。
父元素:
const elRefs = useRef([]);
if (elRefs.current.length !== otherPhones.length) {
// add or remove refs
elRefs.current = Array(otherPhones.length)
.fill()
.map((_, i) => elRefs.current[i] || createRef());
}
...
const _deleteOtherPhone = index => {
const temp = [...otherPhones];
temp.splice(index, 1);
for (let i = 0; i < temp.length; i++) {
const element = temp[i];
elRefs.current[i].current.removeItem(element);
}
...
}
...
<PhoneNumberPicker
placeholder={i18n.t("other_phone")}
style={{ flex: 10 }}
ref={elRefs.current[i]}
countryHint={countryHint}
onChange={value => {
_handleOtherPhone(value, i);
}}
/>
...
子元素PhoneNumberPicker: 更新电话号码:
removeItem(item) {
this.setState({ phoneNo: item.phoneNumber });
}