React Contenteditable 不关注 Ref

React Contenteditable Not Focusing with Ref

感觉我快疯了 -- 似乎无法克服这个问题。输入任何文本后,我们会立即失去焦点。在 ref 上调用 focus() 似乎完全没有效果。

UpdatePage.js

export default class UpdatePage extends Component {

  constructor(props) {
    super(props);
    const that = this;

    auth.onAuthStateChanged((user) => {
      db.collection('users/' + user.uid + '/updates')
      .onSnapshot(function (querySnapshot) {
        const updates = [];
        querySnapshot.forEach(function (doc) {
          const updateData = doc.data();
          updates.push({...updateData, doc_id: doc.id});
        });
        that.setState({
          updates: updates,
        });
      });
    });
  }

  render() {
    const todaysDate = new Date();

    return (
      <div>
        <UpdateDeck date={todaysDate} {...this.state}/>
      </div>
    );
  }
}

更新牌组

export default class UpdateDeck extends Component {
  render() {
    return <div key={this.props.date}>
      <UpdateCard key={"A"} {...this.props}/>
      <UpdateCard key={"B"} {...this.props}/>
    </div>;
  }
}

UpdateCard.js

export default class UpdateCard extends Component {
  render() {
    return <div>
      <Card>
        <ListGroup>
          {this.props.updates
            .map((update, i) => {
              return <Update key={'Update_' + update.doc_id}
                             update={update}
                             {...this.props}/>;
            })}
        </ListGroup>
      </Card>
    </div>;
  }
}

Update.js:

export default class Update extends Component {

  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  updateCard(doc_id, text) {
    const ref = this.myRef.current;
    db.collection(...).doc(doc_id).update(...)
      .then(function () {
        ref.focus();
      })
  }

  render() {
    return <ContentEditable
        key={this.props.update.doc_id}
        html={this.props.update.text}
        innerRef={this.myRef}
        disabled={false}
        onChange={e => this.updateCard(this.props.update.doc_id, e.target.value)}
      />
  }

}

不用说,db.update() 函数会更新 this.props.update.text,但我想知道这是否是我的问题的根源,因为我没有使用状态。

使用这个 ContentEditable npm 库:https://www.npmjs.com/package/react-contenteditable

您失去焦点的原因是组件正在重新安装而不是重新呈现。

现在发生这种情况的一个原因是因为您向组件添加了一个关键道具,该道具在重新呈现之间发生变化。当发生这种情况时,React 组件已更改并重新安装它。

现在您在 div 上添加一个键 key={this.props.date} 我假设 contentEditable 日期属性的每次更改都可能会导致它的每个子项重新安装

你也不需要 key 道具,除非你从循环中返回元素

您可以像这样简单地编写代码

export default class UpdateDeck extends Component {
  render() {
    return <div>
      <UpdateCard {...this.props}/>
      <UpdateCard {...this.props}/>
    </div>;
  }
}