javascript React Native -从父元件重新转译子元件

f3temu5u  于 2022-11-27  发布在  Java
关注(0)|答案(3)|浏览(124)

我正在尝试修改一个日历-https://github.com/wix/react-native-calendars,这样当我按下某一天时,该天的背景和文本颜色就会改变。我读到要重新呈现一个组件,需要更新父组件的状态,所以这就是我正在尝试的:
Parent.js

export default class InitiateRent extends Component {
  state = {
    ....
    this.markedDays: {},
    someVar: 0
  };

  constructor() {
    super(); 
    this.handler = this.handler.bind(this);
    this.markedDays = {};
  }

  ....

  handler(e) {
    console.log('handler running');
    this.setState({
      someVar: 123
    })
  }

  <Calendar 
    handler={this.handler}
    markedDates={this.markedDays}
    onDayPress={(day)=> {
      console.log('selected day', day);

      var dateString = `'${day.year}-${day.month}-${day.day}'`

      var addDate = {
        [dateString]: {
          customStyles: {
            container: {
              backgroundColor: '#6de3dc',
            },
            text: {
              color: 'white',
              fontWeight: 'bold'
            },
          },
        }
      }

      this.markedDays = Object.assign(addDate, this.markedDays);

      console.log(this.markedDays);
    }}

....

Child.js

pressDay(date) {
    this.props.handler();
    this._handleDayInteraction(date, this.props.onDayPress);
}

renderDay(day, id) { //GETS CALLED IN CHILD RENDER METHOD VIA AN INTERMEDIARY
    ....
        <DayComp
          ....
          onPress={this.pressDay}
          ....
}

除了我没有得到预期的结果之外,其他一切都正常运行--当我在日历上按下一个日期时,处理程序将触发,状态将改变,并且在控制台中,我的对象看起来是正确的:

Object

'2018-9-23': {customStyles: {container: {backgroundColor: "#6de3dc"}, text: {color: "white", fontWeight: "bold"}}}

'2018-9-26': {customStyles: {container: {backgroundColor: "#6de3dc"}, text: {color: "white", fontWeight: "bold"}}}

'2018-9-28': {customStyles: {container: {backgroundColor: "#6de3dc"}, text: {color: "white", fontWeight: "bold"}}}

'2018-9-29': {customStyles: {container: {backgroundColor: "#6de3dc"}, text: {color: "white", fontWeight: "bold"}}}

但是日历上这一天的背景没有改变,文本也没有改变-我必须做什么才能让它重新呈现(改变)?

更新

我创建了一个处理程序链,从最底层的day组件(它只表示日历上的一天)一直到最高级别的父视图(不是App.js,而是在它下面),但仍然没有任何作用。

更新

日历是模态的,我没有任何处理程序来更新它的状态,这会是问题所在吗?

更新

我在文件里找到这个:
!免责声明!请确保markedDates参数不可变。如果更改markedDates对象内容,但对其的引用没有更改,则不会触发日历更新。
这是什么意思?

更新

我试着用一些谷歌搜索来解释这意味着什么,这是否使this.state.markedDays不可变?:

const markedDays = this.state.markedDays;

                var dateString = `'${day.year}-${day.month}-${day.day}'`;

                var addDate = {
                  [dateString]: {
                    customStyles: {
                      container: {
                        backgroundColor: '#6de3dc',
                      },
                      text: {
                        color: 'white',
                        fontWeight: 'bold'
                      },
                    },
                  }
                }

                const markedDaysHolder = {
                  ...markedDays,
                  ...addDate
                }
                
                this.state.markedDays = markedDaysHolder;

更新

我放:

componentDidUpdate(prevProps, prevState, snapshot) {
  console.log("componentDidUpdate in InitiateRent:", prevProps, prevState, snapshot);
}

上面的输出是:

componentDidUpdate in InitiateRent: (3) (index.bundle, line 761)

{initiateRentMessage: function, modalHeight: 200, modalWidth: 200, handler: function}

{modalVisible: true, message: "Hi, I would like to rent an item from you.", rentButtonBackground: "#6de3dc", someVar: 123, markedDays: Object}

undefined

我可以看到状态对象markedDays随着每次按下按钮而变大,为什么样式没有改变?
在所有相关组件中,我注意到它不会在最低阶组件上触发,而最低阶组件是需要更改的组件。

hzbexzde

hzbexzde1#

我也有这个问题,这就是你需要做的

constructor(props) {
    super(props)
    this.state = {
    }
    this.onDayPress = this.onDayPress
  }

showCalendar = () => {
    return (
      <Calendar
        onDayPress={this.onDayPress}
        style={styles.calendar}
        hideExtraDays
        markedDates={{
          [this.state.selected]: {
            selected: true,
            disableTouchEvent: true,
            selectedDotColor: 'orange',
          },
        }}
      />
    )
  }

onDayPress = day => {
    this.setState({
      selected: day.dateString,
    })
  }
vxbzzdmp

vxbzzdmp2#

这是我想做的事情的答案。我希望能够通过点击它来选择和取消选择一个日期(取消选择是@HaiderAli帮助后的问题):
我所要做的就是:

onDayPress = (day) => {
  const _selectedDay = day.dateString;
  let marked = true;
  if (this.state._markedDates[_selectedDay]) {
    // Already in marked dates, so reverse current marked state
    marked = !this.state._markedDates[_selectedDay].selected;
    console.log('marked:', marked);
  }
          
  // Create a new object using object property spread since it should be immutable
  // Reading: https://davidwalsh.name/merge-objects
  const updatedMarkedDates = {
    ...this.state._markedDates,
    ...{
      [_selectedDay]: {
        'selected': marked,
        customStyles: {
          container: {
            backgroundColor: '#6de3dc',
          },
          text: {
            color: 'white',
            fontWeight: 'bold'
          },
        },
      }
    }
  }

  // Triggers component to render again, picking up the new state
  this.setState({ _markedDates: updatedMarkedDates });
}

我添加了'selected':,它需要在那里,这个函数改进了@HaiderAli的答案。
要使取消选择生效,请打开node_modules/react-native-calendars/src/calendar/day/custom/index.js(如果您没有在日历上使用markingType={'custom'}属性,则这是错误的文件。如果您没有使用该属性,请编辑node_modules/react-native-calendars/src/calendar/day/basic/index.js)。进行以下更改:

....

render() {
    let containerStyle = [this.style.base];
    let textStyle = [this.style.text];

    let marking = this.props.marking || {};
    if (marking && marking.constructor === Array && marking.length) {
      marking = {
        marking: true
      };
    }
    const isDisabled = typeof marking.disabled !== 'undefined' ? marking.disabled : this.props.state === 'disabled';

    console.log('marking in day:', marking.selected);

    if (marking.selected) {
      containerStyle.push(this.style.selected);
    } else if (isDisabled) {
      textStyle.push(this.style.disabledText);
    } else if (this.props.state === 'today') {
      containerStyle.push(this.style.today);
      textStyle.push(this.style.todayText);

    /********ADD THIS CONDITION********/
    } else if(!marking.selected) { 
      textStyle.push({backgroundColor: '#ffffff', color: '#2d4150'});
    }

....
3htmauhk

3htmauhk3#

import { View, Text, StyleSheet } from 'react-native';
import React, { useState, useEffect } from 'react';
import { Calendar, CalendarList, Agenda } from 'react-native-calendars';

const Calender = () => {
  const [selectedDay, setSelectedDay] = useState();

  return (
    <View style={{ flex: 1, backgroundColor: 'white' }}>
      <Calendar
        style={[styles.calendar, { height: 350 }]}
        onDayPress={(day) => {
          setSelectedDay({ selected: day.dateString });
        }}
        enableSwipeMonths={true}
        markedDates={{
          [selectedDay?.selected]: {
            selected: true,
            disableTouchEvent: true,
            selectedDotColor: 'orange',
          },
        }}
      />
    </View>
  );
};

export default Calender;

相关问题