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

ReactJS中如何通过onSelect事件将选中文本发送至另一个div?

实现textarea选中文本传递到另一个输入框

问题描述

我有两个容器,希望通过onSelect事件将textarea中的选中文本发送到另一个输入框中。目前的实现会将整个段落内容传递过去,我需要仅传递选中的文本,请问该如何实现?

解决方案

要获取textarea中的选中文本,你可以通过事件对象获取当前textarea元素,利用其selectionStart和selectionEnd属性确定选中范围,再从文本内容中截取对应片段即可。

修改后的代码

import React from "react";
import { Box, Grid, TextField } from "@material-ui/core";
import { useState } from "react";

const SendSelectedText = () => {
    const [label1, setLabel1] = useState('');
    const [para, setPara] = useState('This is Old Para');
    
    const handleSelect = (event) => {
        const textarea = event.target;
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        const selectedText = textarea.value.substring(start, end);
        setLabel1(selectedText);
    };

    return (
        <>
            <Box className="sendSelectedTextPage">
                <Grid container spacing={3}>
                    <Grid item xl={6} lg={6} md={6}>
                        <textarea onSelect={handleSelect} value={para} onChange={(e) => setPara(e.target.value)} />
                    </Grid>
                    <Grid item xl={6} lg={6} md={6}>
                        <TextField
                            variant="outlined"
                            size="small"
                            label="Label One"
                            value={label1}
                            multiline
                            rows={3}
                            className="sendSelectedTextPageInput"
                        />
                    </Grid>
                </Grid>
            </Box>
        </>
    );
};

export default SendSelectedText;

关键说明

  • 给textarea补充value和onChange属性,确保文本内容与状态para同步,避免内容不一致问题
  • 重命名事件处理函数为handleSelect,更贴合onSelect事件的语义
  • 通过textarea.selectionStart和textarea.selectionEnd精准定位选中范围,截取对应文本更新到目标输入框的状态中

内容的提问来源于stack exchange,提问作者Rohit Verma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:10:47