我正在尝试创建一个copyToClipboard函数,该函数从页面上的TextField中获取值并在选择“复制”按钮时复制这些值。这是函数:
function copyToClipboard() {
const textArea = document.createElement("textarea");
textArea.innerText = "";
const parentElement = document.getElementById("span");
if (parentElement) {
textArea.value = parentElement.innerText;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("copy");
textArea.remove();
}
}
这是我的TextField:
<Grid id="span" container spacing={8}>
<Grid item xs={6}>
<TextField
fullWidth
label="Last Pulled"
value={formatTimestamp(r.createdAt, "MM/DD/YYYY")}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
className="text"
/>
<TextField
fullWidth
label="Credit History Length(months)"
value={creditHistLength}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
/>
<TextField
fullWidth
label="SSN Match Indicator"
value={r.ssnMatch}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
className="text"
/>
<TextField
fullWidth
label="Date of Birth"
value={formatTimestamp(r.dateOfBirth, "MM/DD/YYYY")}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
className="text"
/>
<TextField
fullWidth
label="FICO"
value={r.fico}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
/>
<TextField
fullWidth
label="Monthly Mortgage Payment"
value={mortgagePayment}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
/>
<TextField
fullWidth
label="Disputed?"
value={r.isDisputed ? "YES" : "NO"}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
/>
<TextField
fullWidth
label="Hit Indicator"
value={r.hitIndicator}
variant="outlined"
margin="normal"
InputProps={{
readOnly: true
}}
/>
</Grid>
</Grid>
这是按钮:
<Button variant="contained" color="primary" onClick={copyToClipboard}>
<FileCopy />
copy to clipboard
</Button>
现在,copyToClipboard函数仅选择并复制每个TextField的标签,而不是选择每个TextField的值。理想情况下,它将同时获取标签和值,但是我将选择只获取值的解决方案。