React Contenteditable不以Ref为焦点

问题描述 投票:0回答:1

感觉自己快疯了--似乎过不了这个坎。输入任何文本后,我们立即失去焦点。调用ref上的focus()似乎完全没有效果。

更新页面.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>;
  }
}

更新卡.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>;
  }
}

更新卡.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.compackagereact-contenteditable

reactjs focus contenteditable ref
1个回答
1
投票

你的焦点丢失的原因是由于组件被重新挂载而不是重新渲染。

这种情况发生的原因之一是你给组件添加了一个关键道具,这个道具在重渲染之间会发生变化。当这种情况发生时,React就会发现组件发生了变化,并重新加载它。

现在你添加了一个关键道具 key={this.props.date} 在div上,我假设每次改变contentEditable的日期道具可能会改变,导致它的每一个子代都重新挂载。

除非你从循环中返回元素,否则你也不需要一个关键道具。

你可以简单地写下你的代码,比如

export default class UpdateDeck extends Component {
  render() {
    return <div>
      <UpdateCard {...this.props}/>
      <UpdateCard {...this.props}/>
    </div>;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.