我基本上希望我的类是我输入的任何对象,以及类中声明的任何其他方法。
Object属性可以是任何东西,并且在构造类时可以命名为任何东西。
const { useState, useEffect } = React;
const { render } = ReactDOM;
const CalendarDatePicker = ({date, onDateChange}) => {
const [year, setYear] = useState();
const [month, setMonth] = useState();
const [day, setDay] = useState();
const [daysInMonth, setDaysInMonth] = useState();
useEffect(() => {
setYear(date.getFullYear());
setMonth(date.getMonth() + 1);
setDay(date.getDate());
}, [date])
useEffect(() => {
let dim = getDaysInMonth(month, year);
setDaysInMonth(dim);
}, [month, year]);
const handleYearChange = event => {
let nd = new Date(event.target.value, month, day);
setYear(nd.getFullYear());
onDateChange(nd);
}
const handleMonthChange = event => {
let nd = new Date(year, event.target.value - 1, day)
setMonth(nd.getMonth() + 1);
onDateChange(nd);
}
const handleDayChange = event => {
let nd = new Date(year, month, event.target.value);
setDay(nd.getDate());
onDateChange(nd);
}
function getDaysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
return (
<div>
<div className="form-group">
<label htmlFor="display-year">Year</label>
<input
type="number"
id="display-year"
name="display-year"
className="form-control form-control-sm"
min="1"
value={year}
onChange={handleYearChange} />
</div>
<div className="form-group">
<label htmlFor="display-month">Month</label>
<input
type="number"
id="display-month"
name="display-month"
className="form-control form-control-sm"
min="1"
max="12"
value={month}
onChange={handleMonthChange} />
</div>
<div className="form-group">
<label htmlFor="display-day">Day</label>
<input
type="number"
id="display-day"
name="display-day"
className="form-control form-control-sm"
min="1"
max={daysInMonth}
value={day}
onChange={handleDayChange} />
</div>
</div>
);
}
const Calendar = props => {
const handleDateChange = event => {
console.log('You can change the `Calendar` during this event when the date changes...', event);
}
return (
<div className="bg-light border border-dark rounded p-1">
<CalendarDatePicker date={props.date} onDateChange={handleDateChange} />
</div>
);
}
render(<Calendar date={new Date(Date.now())} />, document.body);
如果我想这样做,可以通过以下方式实现:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
答案 0 :(得分:1)
选项1:
class TestClass {
// define the methods it needs
}
function TestFactory<T extends Object>(obj: T): TestClass & T {
return Object.assign(new TestClass(), obj)
}
选项2:
class TestClass<T extends Object> {
// define the methods it needs
constructor(o: T) {
Object.assign(this, o)
}
}
function TestFactory<T extends Object>(obj: T): TestClass<T> & T {
return <T>new TestClass(obj)
}