Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

React 如何实现组件顺序调换

image.png

页面设计如图所示,组件1,2,3都是自定义组件,想通过一定条件比如点击按钮、拖拽,调换某两个组件的位置,代码应该如何设计呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

可以通过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);

`


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...