Tengo esta solución para una tarea de reacción y hay algo que no entendí.
// React is loaded and is available as React and ReactDOM // imports should NOT be used 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.ref.current.focus(); } componentDidMount() { this.props.focused && this.ref.current.focus(); } } 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); En componentDidUpdate la tarea es
// When the focused prop is changed from false to true, // and the input is not focused, it should receive focus. Así que prevProps.focused era falso y la negación !prevProps.focused lo hace verdadero.
Y this.props.focused debe ser verdadero para que la condición con el operador lógico && (!prevProps.focused && this.props.focused) pueda ser verdadera.
Pero la tarea dice que no debería ser cierto // and the input is not focused
¿Eso significa que this.props.focused debería ser falso?
¿La condición no sería verdadera con (verdadero && falso)?
¿Alguien puede explicar lo que no estoy viendo?
Nunca verifica si el elemento tiene foco , solo verifica los accesorios.
Esto probablemente debería verse así:
if(!prevProps.focused && this.props.focused && this.ref.current !== document.activeElement) this.ref.current.focus();Pero verificar esto parece innecesario ya que enfocar el elemento enfocado no tiene impacto en el rendimiento.
La "entrada no está enfocada" no se trata del valor de la propiedad focused , sino de si el elemento está realmente enfocado en el DOM . Si this.ref.current no está enfocada, entonces this.ref.current.focus() le dará el foco de teclado a this.ref.current pero si this.ref.current ya está enfocada, entonces this.ref.current.focus() no cambiará nada de todos modos.