Update Toggle
This commit is contained in:
@ -2,50 +2,31 @@
|
|||||||
|
|
||||||
Renders a toggle component.
|
Renders a toggle component.
|
||||||
|
|
||||||
Initialize `state.isToggleOn` to `false`, bind the `handleClick` method to the component's context.
|
Use the `React.useState()` to initialize the `isToggleOn` state variable to `false`.
|
||||||
Use an object, `style`, to hold the styles for individual components and their states.
|
Use an object, `style`, to hold the styles for individual components and their states.
|
||||||
Create a method, `handleClick`, which uses `Component.prototype.setState` to change the component's `state.toggleOn`.
|
Return a `<button>` that alters the component's `isToggledOn` when its `onClick` event is fired and determine the appearance of the content based on `isToggleOn`, applying the appropriate CSS rules from the `style` object.
|
||||||
In the `render()` method, destructure `state` and `style`, create a `<button>` that alters the component's `state` and determine the appearance of the content based on `state.isToggleOn`, applying the appropriate CSS rules from the `style` object.
|
|
||||||
|
|
||||||
```jsx
|
```jsx
|
||||||
class Toggle extends React.Component {
|
function Toggle(props) {
|
||||||
constructor(props) {
|
const [isToggleOn, setIsToggleOn] = React.useState(false);
|
||||||
super(props);
|
style = {
|
||||||
this.state = {
|
|
||||||
isToggleOn: false
|
|
||||||
};
|
|
||||||
this.style = {
|
|
||||||
on: {
|
on: {
|
||||||
backgroundColor: 'green'
|
backgroundColor: "green"
|
||||||
},
|
},
|
||||||
off: {
|
off: {
|
||||||
backgroundColor: 'grey'
|
backgroundColor: "grey"
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
this.handleClick = this.handleClick.bind(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
handleClick() {
|
|
||||||
this.setState(state => ({
|
|
||||||
isToggleOn: !state.isToggleOn
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
render() {
|
|
||||||
const { isToggleOn } = this.state;
|
|
||||||
const { on, off } = this.style;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
onClick={this.handleClick}
|
onClick={() => setIsToggleOn(!isToggleOn)}
|
||||||
style={isToggleOn ? on : off}
|
style={isToggleOn ? style.on : style.off}
|
||||||
>
|
>
|
||||||
{isToggleOn ? 'ON' : 'OFF'}
|
{isToggleOn ? "ON" : "OFF"}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```jsx
|
```jsx
|
||||||
|
|||||||
Reference in New Issue
Block a user