gpt4 book ai didi

javascript - 根据焦点输入显示元素

转载 作者:行者123 更新时间:2023-12-03 00:48:14 25 4
gpt4 key购买 nike

我正在尝试使一段代码更加高效。这个概念是,当您聚焦文本区域时,您会看到一个段落标签,告诉您剩余的字符。目前我有:

import React, { Component } from "react";

class Idea extends Component {
state = {
showCharactersRemaining: false
};

calculateRemaining() {
return 15 - this.props.body.length;
}

onTextAreaFocus = () => {
this.setState(state => {
return { showCharactersRemaining: true };
});
};

onBlur = () => {
this.setState(state => {
return { showCharactersRemaining: false };
});
};

render() {
const { title, body } = this.props;
const { showCharactersRemaining } = this.state;
return (
<div className="idea">
<input type="text" name="title" value={title} />
<textarea
rows="3"
name="body"
maxlength="15"
value={body}
onFocus={this.onTextAreaFocus}
onBlur={this.onBlur}
/>
{showCharactersRemaining && (
<p>{this.calculateRemaining()} characters remaining.</p>
)}
</div>
);
}
}

export default Idea;

它有效,但也依赖于附加到所述文本区域的两种方法才能使其工作。有没有更聪明的方法来使用react?

最佳答案

CSS 可以为您处理它,从而消除了状态和事件处理程序的必要性。运行代码片段以查看其工作原理(我删除了计算字符的逻辑以保持此示例简单)

.charcount {
display: none;
}

textarea:focus+.charcount {
display: block;
}
<div className="idea">
<textarea rows="3" name="body" maxlength="15" value="foo"></textarea>
<p class="charcount">XX characters remaining.</p>
</div>

关于javascript - 根据焦点输入显示元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53158746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com