如何在React中将ref转发到其子组件并更改安装状态?

时间:2019-12-05 10:33:45

标签: javascript reactjs

如果有人出现参加Testdome反应测试,那么您肯定会遇到这个问题。

TextInput组件呈现一个输入元素,该输入元素接受转发给该输入元素的ref。输入组件应接受一个集中的道具。 当聚焦的道具从false更改为true,并且输入未聚焦时,它应该获得聚焦。另外,在componentDidMount生命周期上,如果焦点属性为true,则输入应获得焦点。

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) {
    // The lifecycle will occur when component is mounted
    // If mounted then it will compare the current props with prevProps
    // If true then set the focus for the ref else false 
    if (prevProps.focused !== this.props.focused) {
      this.ref.current.focus()
    }
  }

  componentDidMount() {
    // This lifecycle checks if component has mount for child
    // If mount then chck if child has focus if yes set the state to true/ false
    // for the current ref
    if (this.props.focused) {
      this.setState({
        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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.3.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.0/umd/react-dom.production.min.js"></script>

1 个答案:

答案 0 :(得分:0)

componentDidUpdate(prevProps) {
// The lifecycle will occur when component is mounted
// If mounted then it will compare the current props with prevProps
// If true then set the focus for the ref else false 
    if( prevProps.focused !== this.props.focused ) {
     this.ref.current.focus()
    }
  }
  
  componentDidMount() {
// This lifecycle checks if component has mount for child
// If mount then chck if child has focus if yes set the state to true/ false
// for the current ref
    if(this.props.focused) {
      this.setState({
        focused:this.ref.current.focus()
      })
    }
  }