首页 > 解决方案 > 当值来自父组件时,如何在文本区域中使用拼音键盘?

问题描述

我遇到了一个奇怪的 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>
    );
  }
}

标签: javascriptreactjs

解决方案


我相信您需要监听 event.type compositionend 而不是更新父级的状态 onchange。

有关如何在 React 中实现此功能的完整描述,请参阅本文。


推荐阅读