BL React Coding

Posted on 2022-03-25 12:10:12
Author: 可乐小可爱メ

App.tsx

import { useState, useEffect } from "react";
import axios from "axios";

interface IUserInfo {
id: number;
name: string;
username: string;
email: string;
phone: string;
website: string;
}

export default function IndexPage() {
const url = "/bl-api/users/1";
const [userData, setUserData] = useState({} as IUserInfo);
useEffect(() => {
axios
.get(url)
.then((data: IUserInfo | unknown) => {
if (data) {
setUserData(data);
}
})
.catch((e) => {
const data = {
id: 1,
name: "Ray Yin",
username: "rayyin",
email: "ray@bridgelegal.biz",
phone: "8727040355",
website: "bridgelegal.com",
};
setUserData(data);
});
}, []);
return (
// No need to touch code below
<div className="App">
<h2>User Data</h2>
<p>
<strong>Name: </strong>{" "}
{userData?.name || "(Need to populate name here)"}
</p>
<p>
{" "}
<strong>Website: </strong>
{userData?.website || "(Need to populate website here)"}
</p>
<p>
{" "}
<strong>Email: </strong>
{userData?.email || "(Need to populate email here)"}
</p>
<p>
{" "}
<strong>Phone: </strong>
{userData?.phone || "(Need to populate phone here)"}
</p>
</div>
);
}



count.tsx


import React from "react";
const { Component } = React;

interface IData {
id: number;
value: number;
}

// BL-Counter
class BLCounter extends Component {
constructor(props, context) {
super(props, context);
}
render() {
const { id, value, onIncrement } = this.props;
return (
<div className="bl-counter">
<b>{value}</b>
<div className="bl-counter-handler">
<button
className="button is-decrement bl-small"
onClick={() => onIncrement({ id, value: value - 1 })}
>
-
</button>
<button
className="button is-increment bl-small"
onClick={() => onIncrement({ id, value: value + 1 })}
>
+
</button>
</div>
</div>
);
}
}

function BLTotal({ sum }: { sum: number }) {
return <p> BLTotal: {sum}</p>;
}

export default function CountPage() {
const [data, setData] = React.useState<Array<IData>>([
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
]);

const totalNumber = React.useMemo(() => {
let i = 0;
data.forEach((elm: IData) => {
i += elm.value;
});
return i;
}, [data]);

React.useEffect(() => {
setData([...data, { id: 4, value: 0 }]);
}, []);
// state data for 3 bl-counters

function onChangeCount(payload: IData) {
const { id, value } = payload;
if (id && typeof value === "number") {
const newData = Array.from(data, (elm: IData) => {
if (elm.id === id) {
return { id, value };
} else {
return elm;
}
});
setData(newData);
}
}

return (
<div>
{data.map((counter: IData) => (
<BLCounter
key={counter.id}
id={counter.id}
value={counter.value}
onIncrement={(payload: IData) => onChangeCount(payload)}
onDecrement={(payload: IData) => onChangeCount(payload)}
/>
))}
<BLTotal sum={totalNumber} />
</div>
);
}



当前评论 (0) 登录后评论

暂无评论