我是React Native的新手。我有一个包含日期和显示日期的数组。我的代码中有一个问题。当我打开一个日期选择器时,它也会打开另一个日期选取器。
因此,如何一次只打开一个日期选择器。帮我开发。
我使用了这个库@react native community/datetimepicker。
这是输出我的代码。非实际行为
如果你有任何解决方案,请告诉我。
这是我的密码。
阵列:
var Data = [
{Id: 1, name: 'ajay', date: '21/02/2021'},
{Id: 2, name: 'vijay',date: '12/02/2022'},
{Id: 3, name: 'zoya',date: '04/05/2023'},
]
const onChange = (event, selectedDate) => {
const currentDate = selectedDate;
setDate(currentDate);
};
const showDatepicker = () => {
setShow(true);
};
<View style={{marginTop:50}}>
{
Data.map((d, index)=> {
return(
<View style={{margin:10}} key={index}>
<Text>{d.name}</Text>
<TouchableOpacity onPress={showDatepicker}>
<Text>{`${date.getDate()}/${date.getMonth() +1}/${date.getFullYear()}`}</Text>
</TouchableOpacity>
{show && (
<DateTimePicker
testID="dateTimePicker"
value={date}
mode={mode}
is24Hour={true}
display="default"
onChange={onChange}
/>
)}
</View>
)
})
}
</View>
试试这些。
const [dateList, setDateList] = useState([]);
const [showDates, setShowDates] = useState({});
useEffect(() => {
setDateList([
{Id: 1, name: 'ajay', date: '21/02/2021'},
{Id: 2, name: 'vijay',date: '12/02/2022'},
{Id: 3, name: 'zoya',date: '04/05/2023'},
]);
},[])
useEffect(() => {
let dates = {};
dateList.map((date,index) => {
dates[date.Id]= false;
if(index == 0)
dates[date.Id] = true;
})
setShowDates(dates);
},[dateList])
const onChange = (event, selectedDate) => {
const currentDate = selectedDate;
setDate(currentDate);
};
const showDatepicker = (item) => {
let dates = {};
Object.keys(showDates).map(d => {
dates[d.Id] = false;
})
dates[item.Id] = true;
setShowDates(dates);
};
<View style={{marginTop:50}}>
{
dateList.map((d, index)=> {
return(
<View style={{margin:10}} key={index}>
<Text>{d.name}</Text>
<TouchableOpacity onPress={showDatepicker.bind(this,d)}>
<Text>{`${date.getDate()}/${date.getMonth() +1}/${date.getFullYear()}`}</Text>
</TouchableOpacity>
{showDates[d.Id]&& (
<DateTimePicker
testID="dateTimePicker"
value={date}
mode={mode}
is24Hour={true}
display="default"
onChange={onChange}
/>
)}
</View>
)
})
}
</View>