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

我正在构建一个待办事项列表应用程序,我想长按各个待办事项,将其颜色更改为绿色,以便将它们标记为已完成。


我的 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,

          }

    })

但是,它不起作用...我做错了什么?有没有我缺少的简单解决方案...


富国沪深
浏览 140回答 2
2回答

摇曳的蔷薇

您可以对代码进行一些更改将颜色选择移至 ListItem 并传递一个 prop 来决定无需在项目本身内创建整个样式,您可以传递要覆盖的样式因此,要执行此操作,您必须从列表项开始<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);  };

拉风的咖菲猫

试试这个方法const longPressHandler = (index) => {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const newTodos = [...todos];&nbsp; &nbsp; newTodos[index].color = (newTodos[index].color && newTodos[index].color == 'green') ? 'white' : 'green';&nbsp; &nbsp; setTodos(newTodos);&nbsp; &nbsp;&nbsp;}<FlatList&nbsp; &nbsp; &nbsp;data={todos}&nbsp; &nbsp; &nbsp;renderItem={( {item, index} ) => (&nbsp; &nbsp; &nbsp; &nbsp; <ListItem&nbsp; &nbsp; &nbsp; &nbsp;item={item}&nbsp; &nbsp; &nbsp; &nbsp;index={index}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;longPressHandler = {longPressHandler}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;color={item.color || 'white'}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;pressHandler = {pressHandler}&nbsp; &nbsp; />&nbsp; &nbsp;)}/>export default function ListItem(props) {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <TouchableOpacity onLongPress={() => props.longPressHandler(props.index)} >&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.....&nbsp; &nbsp; &nbsp; &nbsp; </TouchableOpacity>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; )}注意:您必须将索引从 renderItem 传递到 ListItem,并从 ListItem 传递到 longPressHandler 函数
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript