Reactjs 使用React defaultProps正确设置道具的初始状态

Reactjs 使用React defaultProps正确设置道具的初始状态,reactjs,Reactjs,我的问题是关于焦点问题,来自: 我走了这么远: class Input extends React.PureComponent { render() { let {forwardedRef, ...otherProps} = this.props; return <input {...otherProps} ref={forwardedRef} />; } } const TextInput = React.forwardRef((props, ref)

我的问题是关于焦点问题,来自:

我走了这么远:

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);
所以我得到了第二个正确的测试,但不是第一个,一个要求道具的测试。初始状态为true


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

我不会在它下面签名,但这正是该练习所期望的。如果
focused
prop为
true
,则必须将输入集中在
componentDidMount
中。此外,如果
聚焦
道具更改,也必须更改聚焦

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} />;
  }
}
类FocusableInput扩展了React.Component{
裁判;
componentDidUpdate(prevProps){
如果(prevProps.focused!==此.props.focused){
这个.ref.focus();
}
}
componentDidMount(){
如果(这个。道具。聚焦){
这个.ref.focus();
}
}
render(){
返回this.ref=ref}/>;
}
}

我仍然想解决这个问题。有人能解释一下吗?这个.ref.focus()需要是这个.ref.current.focus(),但是是的,现在两个测试都通过了:D@logan我更喜欢使用回调引用:)
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} />;
  }
}