You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用React+styled-components实现老式手机UI字符串光标移动求助

实现光标自由移动的修改步骤

1. 调整组件渲染逻辑

删除Phone组件return中Screen标签内的冗余代码,按照光标位置拆分输入的字符串,把光标组件插入到对应位置即可:

return (
    <Container>
        <Screen> 
            {/* 按光标位置拆分字符串,插入闪烁光标 */}
            <span>{number.slice(0, position)}</span>
            <Cursor />
            <span>{number.slice(position)}</span>
        </Screen>  

        {position}
        <Keyboard>
            <button onClick={() => onUpClicked()}>⬆</button>
            <button onClick={() => onDownClicked()}>⬇</button>
            <button onClick={() => onRemoveChar()}>⌫</button>
            <button disabled>1</button>
            <button onClick={() => onBtnClicked('2')}>2 abc</button>
            <button onClick={() => onBtnClicked('3')}>3 def</button>
            <button onClick={() => onBtnClicked('4')}>4 ghi</button>
            <button onClick={() => onBtnClicked('5')}>5 jkl</button>
            <button onClick={() => onBtnClicked('6')}>6 mno</button>
            <button onClick={() => onBtnClicked('7')}>7 pqrs</button>
            <button onClick={() => onBtnClicked('8')}>8 tuv</button>
            <button onClick={() => onBtnClicked('9')}>9 wxyz</button>
            <button disabled>*</button>
            <button disabled>0 ⌴</button>
            <button disabled>#</button>
        </Keyboard> 
    </Container>
)

2. 优化样式避免错位

补充对齐相关样式,确保光标和文字高度匹配不会错位:

/* 修改Screen样式 */
export const Screen = styled.div`
    padding: 1rem 2rem;
    border: 0;
    border-radius: 0.25rem;
    background: var(--white);
    width: 15rem;
    height: 8rem;
    /* 新增以下样式 */
    display: flex;
    align-items: flex-start;
    font-size: 1rem;
    line-height: 1.5;
`

/* 修改Cursor样式 */
export const Cursor = styled.span`
    animation: blink 1.5s linear infinite alternate;
    border-color: #333;
    border-left: 1px solid;
    margin-left: -1px;
    /* 新增以下样式 */
    line-height: 1.5;
    height: 1.5rem;
`

3. 功能验证

你现有的光标移动、插入字符、删除字符的业务逻辑已经完全符合要求,修改完上述内容后即可实现预期效果:

  • 按⬆键光标向左移动一位
  • 按⬇键光标向右移动一位
  • 在非末尾位置输入字符会直接插入到光标所在位置,光标自动后移
  • 按删除键会删除光标前一位的字符,光标自动前移

内容的提问来源于stack exchange,提问作者Alexandre Bonfim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:45:06