javascript - 当值来自父组件时,如何在文本区域中使用拼音键盘?
问题描述
我遇到了一个奇怪的 textareas 反应问题!目前,我们的应用程序将 textarea 的值从父组件发送给它的子组件,然后子组件只渲染 textarea(它做了一些其他的事情,但为了简单起见)。当该字段接收到 onInput 事件时,它将使用其新文本更新父级。如果您当前在该字段中输入,则正确的英文字符会将其添加到父级并返回到子级。但是,当使用拼音键盘(在我的情况下,特别是 mac 的拼音键盘)时,不会出现选择中文字符的提示。我能够使用带有输入和 onchange 事件的拼音键盘,但是我们的要求指定了一个文本区域。我尝试使用 onChange 事件和按键事件,但没有成功。我能够成功地重现基于类和功能组件的问题,但是我们的应用程序的组件使用类组件。任何关于为什么在文本区域中键入时不显示拼音键盘提示的任何想法将不胜感激!
类组件:https ://codepen.io/Zozoobaba/pen/poEgMoj
功能组件:https ://codepen.io/Zozoobaba/pen/yLaemga
class Field extends React.Component {
constructor(props){
super(props);
this.state = {
previousText: props.text,
currentText: props.text,
};
this.compareText = this.compareText.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({
previousText: nextProps.text,
currentText: nextProps.text,
});
}
compareText(e){
const { currentText } = this.state;
const { value } = e.target;
this.setState({previousText: currentText}, () => this.props.updateText(value))
}
render() {
const { state } = this;
return (
<textarea
value={state.currentText}
onInput={(e) => {this.compareText(e)}}
/>
)
}
}
const Appication = (props) => {
const [textareaText, setTextareaText] = useState('');
const updateText = (text) => {
setTextareaText(text);
}
render() {
// console.log(this.state.textareaText)
return (
<div className="form">
<div className="header">
<h1>Welcome!</h1>
<p>Please provide your information below.</p>
</div>
<div className="inputcontainer">
<div>{this.state.textAreaText}</div>
<Field updateText={this.updateText} text={this.state.textareaText} />
</div>
</div>
);
}
}
class Application extends React.Component {
constructor(props){
super(props);
this.state = {
textareaText: '',
}
this.updateText = this.updateText.bind(this);
}
updateText(text){
this.setState({textareaText: text})
}
render() {
// console.log(this.state.textareaText)
return (
<div className="form">
<div className="header">
<h1>Welcome!</h1>
<p>Please provide your information below.</p>
</div>
<div className="inputcontainer">
<div>{this.state.textAreaText}</div>
<Field updateText={this.updateText} text={this.state.textareaText} />
</div>
</div>
);
}
}
解决方案
我相信您需要监听 event.type compositionend 而不是更新父级的状态 onchange。
推荐阅读
- bash - 仅在一列中消除两个 ^ 字符后的所有内容
- c++ - C++ 处理 bad_alloc 异常,C2276 错误代码
- c++ - 关于 C++ 中运算符优先级的问题
- python - ScrapySplash javascript页面不会呈现
- java - 使用 Spring-Data-Rest,如何从一个 REST 调用更新 OneToOne 关系双方的 FK?
- laravel - 在下拉列表中显示特定数据
- vba - 从 Access VBA 在 SQL 中保存 jpg
- wordpress - 删除分页的最后一页
- sql - “SELECT TOP”查询的意外 SQL 行为
- python - 填充颜色不适用于我的函数(Python 乌龟图形)