【问题标题】:TestDome - REACT - 1. FocusTestDome - REACT - 1. 专注
【发布时间】:2020-02-24 21:42:18
【问题描述】:

TextInput 组件在 DOM 中呈现一个输入元素,然后 接受转发到该输入元素的 ref。完成 FocusableInput 组件:

组件应该接受一个有焦点的道具。 当focused prop 从false 变为true,并且输入没有聚焦时,它应该获得焦点。 如果在安装focused prop 时为真,则输入应获得焦点。

  render() {
    let {forwardedRef, ...otherProps} = this.props; 
    return <input {...otherProps} ref={forwardedRef} />;
  }
}

const TextInput = React.forwardRef((props, ref) => {
  return <Input {...props} forwardedRef={ref} />
});

class FocusableInput extends React.Component {

  ref = React.createRef()

  render() {
    return <TextInput ref={this.ref} />;
  }

  // When the focused prop is changed from false to true, 
  // and the input is not focused, it should receive focus.
  // If focused prop is true, the input should receive the focus.
  // Implement your solution below:
  componentDidUpdate(prevProps) {}

  componentDidMount() {}
}

FocusableInput.defaultProps = {
  focused: false
};

const App = (props) => <FocusableInput focused={props.focused} />;

document.body.innerHTML = "<div id='root'></div>";
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);``` 

> I don't get what they want me to do.. does anyone have the solution
> for this?
> 
> https://www.testdome.com/d/react-js-interview-questions/304

【问题讨论】:

  • 请edit您的问题将标题更新为有意义的内容。现在,很难从标题中猜出你的问题是什么。请参阅How to Ask 了解更多信息。
  • 请看How to Ask页面:这里目前没有问题,只是一个需求列表。

标签: reactjs


【解决方案1】:

componentDidUpdate & ComponentDidMount 函数应该是这样的:

 componentDidUpdate(prevProps) {
    if(prevProps.focused != this.props.focused && this.props.focused){
      this.ref.current.focus();
    }
  }

  componentDidMount() {
    if(this.props.focused){
      this.ref.current.focus();
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多