You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.9 KiB
68 lines
1.9 KiB
import React, { Component } from 'react'; |
|
import Box from './box'; |
|
// Boxes: 父组件 Box: 子组件 |
|
class Boxes extends Component { |
|
state = { |
|
boxes: [ |
|
{id: 1, x: 1}, |
|
{id: 2, x: 2}, |
|
{id: 3, x: 3}, |
|
{id: 4, x: 4}, |
|
] |
|
} |
|
|
|
// 每个组件的state只能在该组件内访问!!!! |
|
handleDelete = (BoxId) => { |
|
// 保留所有id不同于BoxId的元素 |
|
const boxes = this.state.boxes.filter(box => box.id !== BoxId); |
|
this.setState({boxes: boxes}); |
|
|
|
} |
|
|
|
handleReset = () => { |
|
const boxes = this.state.boxes.map(box => { |
|
return { |
|
id: box.id, |
|
x: box.id, |
|
} |
|
}); |
|
|
|
this.setState({boxes:boxes}); |
|
} |
|
|
|
|
|
handleClickLeft = (box,step) => { |
|
const boxes = [...this.state.boxes]; // 浅拷贝 |
|
const k = boxes.indexOf(box); // box对应的index |
|
boxes[k].x = Math.max(0,boxes[k].x - step);// 修改state中的x值 |
|
this.setState({boxes}); |
|
|
|
} |
|
|
|
handleClickRight = (box,step) => { |
|
const boxes = [...this.state.boxes]; // 浅拷贝 |
|
const k = boxes.indexOf(box); // box对应的index |
|
boxes[k].x = Math.min(1000,boxes[k].x + step); // 修改state中的x值 |
|
this.setState({boxes}); |
|
} |
|
|
|
render() { |
|
// 父元素给子元素传递数据 |
|
return ( |
|
<React.Fragment> |
|
<button onClick={this.handleReset} style={{marginTop: "5px"}} className='btn btn-warning btn-sm'>Reset</button> |
|
{this.state.boxes.map(box => ( |
|
<Box key={box.id} |
|
box={box} |
|
onDelete={this.handleDelete} |
|
onLeft={this.handleClickLeft} |
|
onRight={this.handleClickRight} |
|
> |
|
</Box> |
|
))} |
|
</React.Fragment> |
|
); |
|
} |
|
} |
|
|
|
export default Boxes; |