好的,伙计们。
我正在处理<TimePicker/>
中的React
第三方库,并希望操纵状态,以便稍后将这种新的代码格式推送到新的object
中。
当我使用该库作为目标值时,无论选择什么时间,我的状态都会变成这样的字符串-例如,如果选择20:30,则this.state.time
等于"20:30"
。
我想将此string
操纵成这样的对象:
从"20:30"
到time: {hour: 20, minutes: 30}
///小时和分钟现在都是数字
我的完整代码如下:
import React from "react";
import TimePicker from "react-time-picker";
import './Clock.css'
class Clock extends React.Component {
state = {
time: '0:00',
pushTime: [],
value: ''
};
onChangeTimePickerHandler = time => {
this.setState({time});
let currentTime = this.state.time;
this.props.CallbackRenderTime(currentTime)
};
//I am using TimePicker library for React and want to manipulate the income from the chosen time
pushNewTimeHandler = () => {
let time = [...this.state.time] ;// ["1", "0", ":", "0", "0"]
time.splice(2, 1);
let timeToOneString = time.join().replace(/,/g, "");
let prepareStringForNewObject = (value, index) => {
let array = value.substring(0,index) + ',' + value.substring(index);
return array.split(',')
};
let newObj = {...prepareStringForNewObject(timeToOneString,2)};
console.log(newObj); // {0: "10", 1: "00"}
};
render() {
return (
<div>
<TimePicker
onChange={this.onChangeTimePickerHandler}
value={this.state.time}/>
<button onClick={this.pushNewTimeHandler}>Push the Array of Time</button>
<p>{this.state.time}</p>
</div>
)
}
}
export default Clock
所以我一直在玩耍,并提出了这个非常丑陋的问题解决方案:
//I am using TimePicker library for React and want to manipulate the income from the chosen time
manipulateTimeHandler = () => {
//this.state.time is "10:00"
let time = [...this.state.time] ;// now it looks like this: ["1", "0", ":", "0", "0"]
time.splice(2, 1);
let timeToOneString = time.join().replace(/,/g, "");
let prepareStringForNewObject = (value, index) => {
let array = value.substring(0,index) + ',' + value.substring(index);
return array.split(',')
};
let newObj = {...prepareStringForNewObject(timeToOneString,2)};
console.log(newObj); //finally it became the object, but the object values are still
//strings and the object keys still need to be changed into "hour"
//and "minutes" {0: "10", 1: "00"}
};
因此,在我的丑陋解决方案pushNewTimeHandler
上,我仍然需要将对象键重命名为hour
和minutes
,还需要将小时和分钟的字符串值转换为数字。>
答案 0 :(得分:1)
我将时间字符串除以:
,创建了一个字符串数组,然后将每个字符串映射为一个数字,并在左侧的左侧解构为hour
和minutes
=
。然后,您可以创建hour
和minutes
的对象:
const str = '20:30';
const [hour, minutes] = str.split(':').map(Number);
const obj = { hour, minutes };
console.log(obj);