好的,伙计们
我正在与<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
,还需要将小时和分钟的字符串值转换为数字。
我分裂由时间串:
,产生一个字符串数组,则每个串的数字,并且解构映射到hour
与minutes
左边的=
。然后你就可以做出的一个目标hour
和minutes
:
const str = '20:30';
const [hour, minutes] = str.split(':').map(Number);
const obj = { hour, minutes };
console.log(obj);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句