React Native-从父组件重新渲染子组件

时间:2018-09-21 17:15:05

标签: javascript react-native components rendering parent-child

我正在尝试修改日历-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对象的内容,但不更改对它的引用   更改日历更新将不会触发。

这是什么意思?

更新

我试图解释一些Go​​ogle搜索的含义,这会使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在此输出中每按一次按钮就会变大,为什么样式没有改变?

在所有相关组件中,我注意到它并没有在最低级别的组件上触发,这是需要更改的组件。

2 个答案:

答案 0 :(得分:2)

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

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,
    })
  }

答案 1 :(得分:2)

这是我试图做的事情的回答。我希望能够通过按一个日期来选择和取消选择一个日期(在@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'});
    }

....
相关问题