如何在react native上更新动态组件的文本?

时间:2019-02-11 01:54:44

标签: reactjs react-native

我是React和Native的新手,我想展示一个由以下组成的组件:

Schedule

因此,当用户选中相应的复选框时,我转换了提到的组件,并添加了另一个类似于以下内容的视图:

enter image description here

当用户单击Text元素时出现问题,因为我显示了一个模式以选择所需的小时和分钟,并且当该模式关闭时,我假装更新状态,并使用选定的时间更新了Text元素,但是它不起作用,有什么建议吗?

这是我的代码:

 import React from 'react';
    import {View,Text, TextInput, StyleSheet,TouchableOpacity} from 'react-native';
    import { CheckBox } from 'react-native-elements';
    import DateTimePicker from 'react-native-modal-datetime-picker';

    let frmHoras; 

    export default class CustomChkHorario extends React.Component{

        constructor(props){
            super(props);
            this.state={
                chk:false,
                fontColor:'black',
                title:'Closed',
                isDateTimePickerVisible: false,
                sTimeMonday:'00:00',
                eTimeMonday:'00:00'
            }
        }

        _showDateTimePicker = () => {
            this.setState({ isDateTimePickerVisible: true });
        }

        _hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false });

        _handleDatePicked = (date) => {
          console.log('A date has been picked: ', date);
          this.setState({sTimeMonday:date});
          this._hideDateTimePicker();
        };

        pressedChk = () => {
            //console.log('checked:',this.state.checked);
            this.setState({chk:!this.state.chk}, () =>{
                if(this.state.chk==false){
                    this.setState({fontColor:'black', title:'Closed'});
                    frmHoras=null;
                }else{
                    this.setState({fontColor:'green', title:'Open'});
                    frmHoras=
                        <View style={{flexDirection:'row',alignItems:'center'}}>
                            <Text>from:</Text> 
                            <TouchableOpacity onPress={this._showDateTimePicker}>
                                <Text style={styles.input}>{this.state.sTimeMonday}</Text>
                            </TouchableOpacity>
                            <Text>to:</Text>
                            <TouchableOpacity onPress={this._showDateTimePicker}>
                                <Text style={styles.input}></Text>
                            </TouchableOpacity>
                        </View>;
                }
            });


        }

        render(){
            return(
                <View style={{alignItems:'center'}}>
                    <View style={{flexDirection:'row',justifyContent:'center',alignItems:'center'}}>
                        <Text>{this.props.dia}</Text>
                        <CheckBox title={this.state.title}
                            checked={this.state.chk}
                            onPress={this.pressedChk}
                            checkedColor='green'
                            textStyle={{color:this.state.fontColor}}></CheckBox>
                    </View>
                    <View>
                        {frmHoras}
                    </View>
                    <DateTimePicker
                        isVisible={this.state.isDateTimePickerVisible}
                        onConfirm={this._handleDatePicked}
                        onCancel={this._hideDateTimePicker}
                        mode={'time'}
                    />
                </View>
            );        
        }
    }

    const styles = StyleSheet.create({
        input: {
            marginHorizontal: 10,     
            height:25,
            width:60,
            borderBottomColor:'black',
            borderStyle:'solid',
            borderBottomWidth:1,
            margin:10
        }
    });

2 个答案:

答案 0 :(得分:1)

您应该在函数中呈现frmHoras,但是您当前正在setState回调中执行此操作,这在您的情况下会产生误导,因为在{ {1}}完成并重新渲染组件。看一下document,其中清楚提到了这种行为

  

setState()的第二个参数是可选的回调函数,将在setState完成并重新渲染组件后执行。

因此,更改如下

创建一个将呈现setState的新函数,使其为setState

frmHoras

下一步,更新renderFrmHoras以设置renderFrmHoras = () => { const { chk } = this.state; if(!chk) { return null; } return ( <View style={{flexDirection:'row',alignItems:'center'}}> <Text>from:</Text> <TouchableOpacity onPress={this._showDateTimePicker}> <Text style={styles.input}>{this.state.sTimeMonday}</Text> </TouchableOpacity> <Text>to:</Text> <TouchableOpacity onPress={this._showDateTimePicker}> <Text style={styles.input}></Text> </TouchableOpacity> </View>; ); } pressedChkfontColor

title

接下来,在render方法中,只需调用chk函数

pressedChk = () => {
  this.setState((prevState) => {
    return ({
      chk: !prevState.chk,
      fontColor: !prevState.chk ? 'green' : 'black',
      title: !prevState.chk ? 'Open' : 'Closed'
    });
  })
}

希望这会有所帮助!

答案 1 :(得分:1)

  _handleDatePicked = date => {
    const time = new Date(date);
    const timePicked = `${time.getHours()}:${time.getMinutes()}`;

    this.setState({ sTimeMonday: timePicked });
    this._hideDateTimePicker();
  };

  pressedChk = () => {
    this.setState({ chk: !this.state.chk }, () => {
      if (this.state.chk) {
        this.setState({ fontColor: 'green', title: 'Open' });
      } else {
        this.setState({ fontColor: 'black', title: 'Closed' });
      }
    });
  };

  render() {
    return (
      <View style={{ alignItems: 'center' }}>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <Text>{this.props.dia}</Text>
          <CheckBox
            title={this.state.title}
            checked={this.state.chk}
            onPress={this.pressedChk}
            checkedColor="green"
            textStyle={{ color: this.state.fontColor }}
          />
        </View>
        {this.state.chk && (
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <Text>from:</Text>
            <TouchableOpacity onPress={this._showDateTimePicker}>
              <Text style={styles.input}>{this.state.sTimeMonday}</Text>
            </TouchableOpacity>
            <Text>to:</Text>
            <TouchableOpacity onPress={this._showDateTimePicker}>
              <Text style={styles.input} />
            </TouchableOpacity>
          </View>
        )}
        <DateTimePicker
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this._handleDatePicked}
          onCancel={this._hideDateTimePicker}
          mode={'time'}
        />
      </View>
    );
  }
}