首页 > 解决方案 > 使用 React defaultProps 正确设置 prop 的初始状态

问题描述

我的问题是关于焦点问题的: 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

所以我得到了第二个测试正确但不是第一个,那个要求 props.focused 的初始状态为真。

查看我的代码,似乎我已经将其设置为 true?

标签: reactjs

解决方案


我不会在它下面签名,但这是该练习所期望的。如果focusedprop 是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} />;
  }
}

推荐阅读