React 如何实现组件顺序调换
页面设计如图所示,组件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);
`
以上是 React 如何实现组件顺序调换 的全部内容, 来源链接: utcz.com/a/63084.html