mirror of
https://github.com/bendtherules/react-hooks-with-class.git
synced 2026-08-19 00:33:52 +00:00
Add alternate demo with hooks mocking in classes
This commit is contained in:
+71
@@ -0,0 +1,71 @@
|
|||||||
|
import React, { Component } from "react";
|
||||||
|
|
||||||
|
import Form from "./Form";
|
||||||
|
import "./App.css";
|
||||||
|
|
||||||
|
export default class App extends Component {
|
||||||
|
constructor(props) {
|
||||||
|
super(props);
|
||||||
|
[this.getTodos, this.setTodos] = this.useState('todos', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
useState(key, initialValue) {
|
||||||
|
this.state = {
|
||||||
|
...this.state,
|
||||||
|
[key]: initialValue,
|
||||||
|
};
|
||||||
|
|
||||||
|
return ([
|
||||||
|
// get function
|
||||||
|
() => {
|
||||||
|
// debugger;
|
||||||
|
return this.state[key];
|
||||||
|
},
|
||||||
|
|
||||||
|
// set function
|
||||||
|
(newValue) => {
|
||||||
|
return this.setState({
|
||||||
|
[key]: newValue,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
toggleComplete = (i) => {
|
||||||
|
this.this.setTodos(
|
||||||
|
this.getTodos().map(
|
||||||
|
(todo, k) =>
|
||||||
|
k === i
|
||||||
|
? {
|
||||||
|
...todo,
|
||||||
|
complete: !todo.complete
|
||||||
|
}
|
||||||
|
: todo
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
return (
|
||||||
|
<div className="App" >
|
||||||
|
<Form
|
||||||
|
onSubmit={text => this.setTodos([{ text, complete: false }, ...this.getTodos()])}
|
||||||
|
/>
|
||||||
|
<div>
|
||||||
|
{this.getTodos().map(({ text, complete }, i) => (
|
||||||
|
<div
|
||||||
|
key={text}
|
||||||
|
onClick={() => this.toggleComplete(i)}
|
||||||
|
style={{
|
||||||
|
textDecoration: complete ? "line-through" : ""
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{text}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<button onClick={() => this.setTodos([])}>reset</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import ReactDOM from "react-dom";
|
import ReactDOM from "react-dom";
|
||||||
import App from "./App";
|
import App from "./App2";
|
||||||
import * as serviceWorker from "./serviceWorker";
|
import * as serviceWorker from "./serviceWorker";
|
||||||
|
|
||||||
ReactDOM.render(<App />, document.getElementById("root"));
|
ReactDOM.render(<App />, document.getElementById("root"));
|
||||||
|
|||||||
Reference in New Issue
Block a user