为了账号安全,请及时绑定邮箱和手机立即绑定

将局部变量传递给 React Native 中的组件

将局部变量传递给 React Native 中的组件

富国沪深 2023-07-14 10:40:15
我正在构建一个待办事项列表应用程序,我想长按各个待办事项,将其颜色更改为绿色,以便将它们标记为已完成。我的 App.js 内部有一个var color = 'white';组件,还有另一个名为 listItem 的组件用于列表项。我有这个非常基本的功能来改变颜色const longPressHandler = () => {    (color == 'white') ? color = 'green' : color = 'white';  }我正在发送colorlistItem 的 via 属性<ListItem item={item} longPressHandler = {longPressHandler} color={color} pressHandler = {pressHandler}/>我按如下方式使用它backgroundColor: props.color检查如下:const styles = StyleSheet.create({        listItem:{            padding: 8,            margin:4,            fontSize: 18,            textAlignVertical:'center',            borderColor:'gray',            borderWidth: 3,            borderStyle: 'solid',            borderRadius:10,            backgroundColor: props.color,          }    })但是,它不起作用...我做错了什么?有没有我缺少的简单解决方案...
查看完整描述

2 回答

?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

您可以对代码进行一些更改

  1. 将颜色选择移至 ListItem 并传递一个 prop 来决定

  2. 无需在项目本身内创建整个样式,您可以传递要覆盖的样式

因此,要执行此操作,您必须从列表项开始

<TouchableOpacity

  onLongPress={() => props.longPressHandler(props.item.key)}

  onPress={() => props.pressHandler(props.item.key)}>

  <Text

    style={[

      // this will make sure that only one style object is created

      styles.listItem,

      { backgroundColor: props.marked ? 'green' : 'white' },

    ]}>

    {props.item.todo}

  </Text>

</TouchableOpacity>

并且您的长按处理程序应如下所示更改,这会将标记的属性设置为您用来决定上面颜色的状态


  const longPressHandler = (key) => {

    const updatedTodos = [...todos];

    const item = updatedTodos.find((x) => x.key == key);

    item.marked = !item.marked;

    setTodos(updatedTodos);

  };

查看完整回答
反对 回复 2023-07-14
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

试试这个方法


const longPressHandler = (index) => {

    

    const newTodos = [...todos];

    newTodos[index].color = (newTodos[index].color && newTodos[index].color == 'green') ? 'white' : 'green';

    setTodos(newTodos);

    

}



<FlatList

     data={todos}

     renderItem={( {item, index} ) => (

        <ListItem

       item={item}

       index={index} 

       longPressHandler = {longPressHandler} 

       color={item.color || 'white'} 

       pressHandler = {pressHandler}

    />

   )}

/>


export default function ListItem(props) {


    return (

        <TouchableOpacity onLongPress={() => props.longPressHandler(props.index)} >

             .....

        </TouchableOpacity>

    

    )

}

注意:您必须将索引从 renderItem 传递到 ListItem,并从 ListItem 传递到 longPressHandler 函数


查看完整回答
反对 回复 2023-07-14
  • 2 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信