使用React defaultProps正确设置prop的初始状态

时间:2019-11-26 01:06:37

标签: reactjs

我的问题是关于焦点问题的: https://www.testdome.com/d/react-js-interview-questions/304

我到这为止了

class Input extends React.PureComponent {
  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) {
    if (prevProps.focused !== this.props.focused && !!this.props.focused)
    {
      if (this.ref.current !== document.activeElement)
      {
        this.ref.current.focus();
      }
    }
  }

  componentDidMount() {}
}

FocusableInput.defaultProps = {
  focused: true
};

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

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

我知道了

The focused property has an initial state of true: Wrong answer 
Changing the focused prop from false to true focuses the input: Correct answer

所以我得到了第二个正确的测试,但没有一个正确,第一个测试是要求道具。测试的重点是初始状态为true。

看我的代码,看来我已经将它设置为true了?

1 个答案:

答案 0 :(得分:0)

我不会在其下签字,但这是该练习所期望的。如果focused属性为true,则必须将输入集中在componentDidMount内。同样,如果focused道具发生变化-焦点也必须改变。

class FocusableInput extends React.Component {
  ref;

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

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

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