ReactJS输入没有得到焦点

ReactJS input does not get focus

本文关键字:焦点 输入 ReactJS      更新时间:2023-09-26

下面是父组件(FundLogo)的代码:

var FundLogo = React.createClass({
getInitialState: function() {
    return { editing: false, img: "img/xxx.gif" };
},
onClick: function() {
    this.setState({ editing: true });
},
onBlur: function(newImg) {
    this.setState({ editing: false, img: newImg});
},
render: function() {
    return(
        <div className="banner_holder adj_height">
            {
                this.state.editing ?
                    <FundEditLogoBox onBlur={ this.onBlur } /> :
                    <img id="fund_logo" src={ this.state.img } onClick={ this.onClick } alt="finvesco logo" />
            }
        </div>
    );
}
});

下面是子组件(funddeditlogobox):

var FundEditLogoBox = React.createClass({
componentDidMount: function() {
    this.refs.editLogoBox.getDOMNode().focus();
    alert("Focus is on: " + document.activeElement);
},
onBlur: function() {
  this.props.onBlur(this.refs.editLogoBox.getDOMNode().value);
},
render: function() {
    return (
        <div>
            <input type="file" onBlur={ this.onBlur } accept="image/*" ref="editLogoBox" />
        </div>
    );
}
});

基本上是我的代码应该做的:

  1. 显示容器中的图像
  2. 当图片被点击时,容器中会显示一个上传按钮,而不是图片。
  3. 如果您点击上传按钮(输入)外,未选择要上传的图像,则显示之前的图像,而不是上传按钮。

我的问题是,输入(从子组件)没有得到任何焦点时,它被挂载。我必须点击它才能获得焦点。此外,警报显示

"Focus is on: [object HTMLBodyElement]"

我在网上到处寻找类似的问题,但没有任何工作,不像其他问题,它似乎不是一个"重新渲染"的问题…谢谢你的帮助!

这就是你需要的:

render: function() {
    return (
      <TextInput
        ref={function(input) {
          if (input != null) {
            input.focus();
          }
        }} />
    );
  },

https://facebook.github.io/react/docs/more-about-refs.html the-ref-callback-attribute