Skip to content

Instantly share code, notes, and snippets.

@Denkong
Created October 23, 2018 09:50
Show Gist options
  • Save Denkong/e25e0b5eff2272c3817543cc7a4dfbfc to your computer and use it in GitHub Desktop.
Save Denkong/e25e0b5eff2272c3817543cc7a4dfbfc to your computer and use it in GitHub Desktop.
TypeScript React - примеры
create-react-app my-app --scripts-version=react-scripts-ts
/-------------------------------------------------------------
import * as React from "react";
/**
* : JSX.Element[]
* : React.FormEvent<HTMLFormElement>
*
* {this.deleteTask.bind(this, value.id)
*/
interface IState {
currentTask: string;
tasks: ITask[];
}
interface ITask {
id: number;
value: string;
completed: boolean;
}
class Form extends React.Component<{}, IState> {
state: IState = {
currentTask: "",
tasks: []
};
_thisInMilliseconds(): number {
const date: Date = new Date();
return date.getTime();
}
handSubmit = (e: React.FormEvent<HTMLFormElement>): void => {
e.preventDefault();
this.setState({
currentTask: "",
tasks: [
...this.state.tasks,
{
completed: false,
id: this._thisInMilliseconds(),
value: this.state.currentTask
}
]
});
};
textchange = (e: any): void => {
this.setState({ currentTask: e.target.value });
};
deleteTask(id: number): void {
console.log("Удаление", id);
const tasks: ITask[] = this.state.tasks.filter(
(task: ITask) => task.id !== id
);
this.setState({ tasks });
}
toggleDone(index: number): void {
const task: ITask[] = this.state.tasks.splice(index, 1);
task[0].completed = !task[0].completed;
const correntTask: ITask[] = [...this.state.tasks, ...task];
this.setState({ tasks: correntTask });
}
renderTasks(): JSX.Element[] {
return this.state.tasks.map((value: ITask, index: number) => {
return (
<div key={value.id}>
{value.value}
<button onClick={this.deleteTask.bind(this, value.id)}>Delete</button>
<button onClick={this.toggleDone.bind(this, index)}>
{value.completed ? "undo" : "done"}
</button>
</div>
);
});
}
public render(): JSX.Element {
return (
<div>
<hr />
App1 ReactTypeScript ToDoList
<form onSubmit={this.handSubmit}>
<input
type="text"
placeholder="add a task"
value={this.state.currentTask}
onChange={this.textchange}
/>
<input type="submit" value="Add Task" />
</form>
<section>{this.renderTasks()}</section>
</div>
);
}
}
export default Form;
/-------------------------------------------------------------
import * as React from "react";
interface IProps {
countBy?: number;
}
interface IState {
count: number;
}
class Description extends React.Component<IProps, IState> {
static defaultProps: Partial<IProps> = {
countBy: 2
};
state: IState = {
count: 0
};
increase = () => {
const countBy: number = this.props.countBy!;
const count = this.state.count + countBy;
this.setState({ count });
};
render() {
return (
<div>
<p>My favorite number is {this.state.count}</p>
<button onClick={this.increase}>Increase</button>
</div>
);
}
}
export default Description;
/-------------------------------------------------------------
import * as React from "react";
interface IProps {
text: string;
age?: number;
}
interface IState {
[key: string]: string;
// email: string;
// test: string;
// name: string;
}
class Form extends React.Component<IProps, IState> {
/*
state: IState = {
email: "",
name: ""
};
handleChange = (e: React.FormEvent): any => {
console.log("handleChange");
const { value, name }: any = e.target;
this.setState({ [name]: value });
console.log(this.state);
};
//или
handleChange = (e: any): any => {
console.log("handleChange");
const { value, name }: any = e.target;
this.setState({ [name]: value });
console.log(this.state);
};
*/
constructor(props: IProps) {
super(props);
this.state = {
email: "",
name: "",
test: "asd"
};
this.handleChange2 = this.handleChange2.bind(this);
}
handleChange2(e: React.FormEvent<HTMLInputElement>) {
console.log("handleChange2");
const value: string = e.currentTarget.value;
const name: string = e.currentTarget.name;
this.setState({ [name]: value });
console.log(this.state);
}
render() {
const { text, age } = this.props;
const { name } = this.state;
return (
<div>
<hr />
form
<div>
{text}
{age}
</div>
<input name="name" value={name} onChange={this.handleChange2} />
</div>
);
}
}
export default Form;
/-------------------------------------------------------------
import * as React from 'react';
interface IMyClassProps{
name?:string;
isMarried:boolean;
}
interface IMyClassState{
age:number
}
class MyClass extends React.Component<IMyClassProps,IMyClassState> {
// Partial - берет из интерфейса переменную и проверяет на тип
// Без него требовало бы isMarried
static defaultProps:Partial<IMyClassProps> = {
name:"Denis"
}
state ={
age:21
}
public render() {
console.log(this.props);
console.log(this.state);
return (
<div>
<hr/>
MyClass
<div>
{this.props.name} {this.state.age}
</div>
</div>
);
}
}
export default MyClass;
/-------------------------------------------------------------
import * as React from "react";
/*
// Запрещается использование TSlint, говорит предпочтительнее interfase
// тк он немного мощьнее
type MyCompProps = {
name: 'qwe' | 'asd'
}
*/
interface IMyCompProps {
name: "qwe" | "asd";
}
const MyComp = (props: IMyCompProps) => {
return (
<div>
<hr />
functional component MyComp
<div>{props.name}</div>
</div>
);
};
export default MyComp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment