在react native中显示来自日期piker的选定日期

jvlzgdj9  于 2022-12-14  发布在  React
关注(0)|答案(3)|浏览(145)

我尝试在react native中使用一个datepiker来控制台日志记录在我单击“我要控制台”按钮时的峰值日期。日志(选定)选定日期

const [text, setTextname] = useState();
const [mydate, setDate] = useState(new Date());
  const [displaymode, setMode] = useState('date');
  const [isDisplayDate, setShow] = useState(false);
    const changeSelectedDate = (event, selectedDate) => {
    const currentDate = selectedDate || mydate;
    let date = moment(selectedDate).format('DD/MM/YYYY');
    console.log('dadad', date);
    setTextname(date);

    setShow(false);
  };
  const showMode = currentMode => {
    setShow(true);
    setMode(currentMode);
  };
  const displayDatepicker = () => {
    showMode('date');
  }; 

  function getdata() {
  
    console.log('sdsds', text);
 
  }

<Button onPress={displayDatepicker} title="Show date picker!" />
        {isDisplayDate && (
          <DateTimePicker
            testID="dateTimePicker"
            value={mydate}
            mode={displaymode}
            is24Hour={true}
            display="default"
            onChange={text => changeSelectedDate()}
            // onChange={changeSelectedDate}
          />
        )}
<View style={styles.buttonw}>
        <Button
          color="#7743DB"
          title="Lets Go"
          type="submit"
          onPress={() => getdata()}
        />
      </View>

我已经显示了datepiker,但我无法选择日期并将其传递给getdata

wrrgggsh

wrrgggsh1#

移除

const [text, setTextname] = useState();

在函数changeSelectedDate中替换

setTextname(date);

setDate(date);

const currentDate = selectedDate || mydate

const currentDate = selectedDate

最后

function getdata() {

console.log('sdsds',mydate);

}

函数更改

const changeSelectedDate = (event, selectedDate) => {

setDate(selectedDate);

setShow(false);
  };

function getdata() {
let date = moment(mydate).format('DD/MM/YYYY');
console.log('sdsds',date);
}
xmq68pz9

xmq68pz92#

您必须在更改日期函数中的setDate状态上设置日期。

setDate(date);----->add this
setTextname(date);
m1m5dgzv

m1m5dgzv3#

可以使用onDateChange方法将日期保存到State

onDateChange={(text) => {console.log(text)}

相关问题