是否有可能使用本机反应构建待办事项列表
我有一个基本列表,可以添加和集中项目,但不能删除项目。
https://snack.expo.io/@morenoh149/todo-list-textinput-spike
import * as React from 'react';
import { TextInput, View } from 'react-native';
export default class App extends React.Component {
currentTextInput = null
state = {
focusedItemId: 0,
items: [
{ id: 0, text: 'the first item' },
{ id: 1, text: 'the second item' },
],
};
addListItem = index => {
let { items } = this.state;
const prefix = items.slice(0, index + 1);
const suffix = items.slice(index + 1, items.length);
const newItem = { id: Date.now(), text: '' };
let result = prefix.concat([newItem]);
result = result.concat(suffix);
this.setState({
focusedItemId: newItem.id,
items: result,
});
};
focusTextInput() {
// focus the current input
this.currentTextInput.focus();
}
componentDidUpdate(_, pState) {
// if focused input id changed and the current text input was set
// call the focus function
if (
pState.focusedItemId !== this.state.focusedItemId
&& this.currentTextInput
) {
this.focusTextInput();
}
}
render() {
const { focusedItemId } = this.state;
return (
<View style={{ flex: 1, justifyContent: 'center' }}>
{this.state.items.map((item, idx) => (
<TextInput
style={{ borderWidth: 1, borderColor: 'black' }}
value={item.text}
ref={item.id === focusedItemId
? c => this.currentTextInput = c
: null}
autoFocus={item.id === focusedItemId}
onChangeText={text => {
const newItems = this.state.items;
newItems[idx].text = text;
this.setState({
items: newItems,
});
}}
onSubmitEditing={event => this.addListItem(idx)}
/>
))}
</View>
);
}
}
答案 0 :(得分:1)
要删除项目,您可以向onKeyPress添加回调,并检查它是否为Backspace(删除)键,以及文本字段是否已为空。如果是这样,则从项目列表中删除该项目。
onKeyPress={({ nativeEvent: { key: keyValue } }) => {
if(keyValue === 'Backspace' && !items[idx].text) {
this.removeListItem(idx)
}
}}
在removeListItem函数中,您可以删除索引处的项目,并将选定的ID更新为列表中先前的ID,以使该ID集中。
removeListItem = index => {
const { items } = this.state;
const newItems = items.filter(item => item.id !== items[index].id)
this.setState({
focusedItemId: items[index - 1] ? items[index - 1].id : -1,
items: newItems.length ? newItems : [this.createNewListItem()],
});
}
请在此处找到完整的工作演示:https://snack.expo.io/@xiel/todo-list-textinput-spike