gpt4 book ai didi

reactjs - 使用数据时的 Material UI 线性进度动画

转载 作者:行者123 更新时间:2023-12-02 17:13:26 24 4
gpt4 key购买 nike

material ui for reactJS 的文档提出了这个用于确定进度条的示例代码。

export default class LinearProgressExampleDeterminate extends React.Component {

constructor(props) {
super(props);

this.state = {
completed: 0,
};
}

componentDidMount() {
this.timer = setTimeout(() => this.progress(5), 1000);
}

componentWillUnmount() {
clearTimeout(this.timer);
}

progress(completed) {
if (completed > 100) {
this.setState({completed: 100});
} else {
this.setState({completed});
const diff = Math.random() * 10;
this.timer = setTimeout(() => this.progress(completed + diff), 1000);
}
}

render() {
return (
<LinearProgress mode="determinate" value={this.state.completed} />
);
}
}

这会创建一个加载动画,直到栏满为止。我试图修改它以使用来自 json 文件的数据,以便它停止在我在每个 json 项目中为其指定的值。我做对了那部分。那是容易的部分。但是动画失败了,因为动画是使用构造函数状态中的 completed 值编写的。而且它也位于我的 data.map 之外,所以我似乎可以找到让它读取 json 文件中的值的方法,以便它可以使用它的超时功能。 :(

这是我的(减少)

JSON

exports.playerItems = [
{
id: 283,
completed: "100",
}
{
id: 284,
completed: "70",
}
{
id: 285,
completed: "20",
}

...

{
id: 295,
completed: "50",
}
]

数据注入(inject)

import PLAYERS from 'data/players.js';
const playersData = PLAYERS['playerItems'];

我的表已映射

<Table>
{playersData.map((row, index) => (
<TableRow id={row.name} key={index}>
<TableRowColumn>

<LinearProgress
mode="determinate"
value={row.completed} />

</TableRowColumn>
</TableRow>
))}
</Table>

我如何修改 progress() 函数,以便它以动画方式显示给 LinearProgress 的值?

提前致谢

最佳答案

您可以将状态更改应用于玩家数据数组,并以增量方式不断更新数组,直到所有玩家都已呈现。

首先,从零开始:

  constructor(props) {
super(props);
this.state = {
playersData: data.map(item => ({ ...item, completed: 0}))
};
};

然后在挂载时启动进程:

  componentDidMount() {
this.timer = setTimeout(() => this.progress(5), 100);
}

更新直到每个玩家都达到 100%:

  progress(completion) {
let done = 0;
this.setState({
playersData: data.map((item, i) => {
const { completed: current } = this.state.playersData[i];
const { completed: max } = item;
if (current + completion >= max) {
done += 1;
}
return {
...item,
completed: Math.min(current + completion, max),
};
}),
});
if (done < data.length) {
this.timer = setTimeout(() => this.progress(5), 100);
}
}

根据需要调整延迟和增量。限制是您需要所有将被渲染的播放器数据,并且它需要作为一个数组处于状态,该数组在单个 setState

中更新

这是关于 codesandbox 的工作示例.

关于reactjs - 使用数据时的 Material UI 线性进度动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47929977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com