页面设计如图所示,组件1,2,3都是自定义组件,想通过一定条件比如点击按钮、拖拽,调换某两个组件的位置,代码应该如何设计呢?
可以通过flex的order属性试试
`
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.container {
display: flex;
flex-direction: column;
}
</style>
`
`
const { Fragment, useState, useCallback } = React;
function createTestComponent() {
return ({ sign, ...others }) => (
<div {...others}>
{sign}
</div>
)
}
const [App1, App2, App3] = [createTestComponent(), createTestComponent(), createTestComponent()];
const App = props => {
const [orders, setOrders] = useState([1,2,3]);
const changeHandle = useCallback(e => {
const value = e.target.value;
if (/^(?:d,){2}d$/.test(value)) {
const arr = value.split(',').map(Number);
setOrders(arr);
}
}, []);
return (
<Fragment>
<div className="container">
<App1 style={{order: orders[0]}} sign={1} />
<App2 style={{order: orders[1]}} sign={2} />
<App3 style={{order: orders[2]}} sign={3} />
</div>
<input onChange={changeHandle}/>
</Fragment>
)
}
ReactDOM.render(<App />, document.body);
`