react-native - 仅更改对象列表中的一个图标 - React Native
问题描述
我希望能够将待办事项列表(见图)中的图标从感叹号更改为复选标记。如果用户将手指放在图标上,或者开发人员在模拟器中用鼠标单击,就会发生这种情况。
通过下面的代码,我设法对其进行了更改,但是仅当我关闭包含列表的模式并重新打开它时,才会出现新图标。所以模态不会重新渲染,既不是部分也不是全部。
如何在单击感叹号图标后立即显示更改?我怀疑它与状态有关,但似乎不可能在 map 函数中创建一个 React 钩子。如果我让 onPress 调用一个函数,那么状态只能在那个外部函数中知道,我不知道如何导出它。
export const TeacherMessages = (props) => {
return (
<View
style={[
styles.borderBox,
props.todos.length > 0 || props.notes.length > 0
? styles.whiteBox
: null,
]}
>
{
props.todos.map((todo) => (
<View key={todo.id} style={styles.listNotes}>
<AntDesign
style={styles.listIcon}
onPress={() => todo.isChecked = true}
name={todo.isChecked ? "checksquare" : "exclamationcircle"}
color={todo.isChecked ? "green" : "red"}
size={18}
/>
<Text style={styles.listText}> {todo.description}</Text>
</View>
))
}
);
解决方案
我认为您需要将 todos 数组存储在一个反应钩子中,这样您对它所做的更改就会立即生效,您可以在父组件中拥有这个 changeTodo 函数并将其作为道具传递,以便从子组件调用它需要的索引。我认为这可能会有所帮助:
export const TeacherMessages = (props) => {
const [todosArr, setTodosArr] = React.useState(props.todos)
const checkTodo = (todoIndex) =>{
let arr = [...todosArr]
arr[todoIndex].isChecked= true
setTodosArr(arr)
}
return (
<View
style={[
styles.borderBox,
todosArr.length > 0 || props.notes.length > 0
? styles.whiteBox
: null,
]}
>
{
todosArr.map((todo, index) => (
<View key={todo.id} style={styles.listNotes}>
<AntDesign
style={styles.listIcon}
onPress={() => checkTodo(index)}
name={todo.isChecked ? "checksquare" : "exclamationcircle"}
color={todo.isChecked ? "green" : "red"}
size={18}
/>
<Text style={styles.listText}> {todo.description}</Text>
</View>
))
}
);
推荐阅读
- mysql - 如何为mysql中的特定行添加值?
- react-native - React Navigation:如何在底部选项卡导航器中触发 navigation.push()?
- pandoc - Citeproc 和 Pandoc Fignos 与 Pandoc 中的“@”冲突?
- java - Recyclerview 适配器:java.util.ArrayList 无法转换为 com.google.firebase.firestore.QuerySnapshot
- r - R:根据列表在数据框中设置变量类型和级别
- c - 使用 Pthread 库在程序输出中切换线程上下文
- c++ - 我们可以在 C++ 中重载模板类,类似于我们重载函数的方式吗?
- python - 如何正确销毁 tkinter 中的顶级小部件
- audio - 需要有关无线音频解决方案硬件堆栈的建议
- google-bigquery - 当文件具有混合数据字段作为列时如何将 jsonl 文件加载到 BigQuery