Guest User

Untitled

a guest
Aug 22nd, 2019
57
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { Component, forwardRef, useRef, useEffect, useImperativeHandle, useState } from 'react';
  2. class App extends Component {
  3. state = { visible: false }
  4. refs = {}
  5. handleClick = () => {
  6. let keys = this.refs.keys()
  7. let visible = keys.every(ref=>this.refs[ref].initializeMessage());
  8. this.setState({ visible });
  9. };
  10. render(){
  11. return(
  12. <wrappedInput value={1} ref={ref1=>this.refs[ref1]} />
  13. <wrappedInput value={2} ref={ref2=>this.refs[ref2]} />
  14. <wrappedInput value={3} ref={ref3=>this.refs[ref3]} />
  15. <MessageBox visible={this.state.visible} />
  16. <button onClick={this.handleClick} />
  17. );
  18. }
  19. }
  20.  
  21. const wrappedInput = forwardRef((props, ref) => {
  22. const [ error, setError ] = useState(false);
  23. const [ message, setMessage ] = useState("");
  24. useEffect(()=>{
  25. if(error){
  26. setMessage("oops");
  27. return error
  28. }
  29. }, [error]);
  30. input = useRef();
  31. useImperativeHandle(ref, ()=>({
  32. focus: ()=>input.current.focus(),
  33. initializeMessage: ()=>{
  34. if(props.value is incorrect) {
  35. setError(true)
  36. } else {
  37. setError(false)
  38. }
  39. }
  40. }));
  41. return(
  42. <div>
  43. <input
  44. ref={ref}
  45. value={props.value}
  46. />
  47. <Icon className={`iconClass ${error ? "errorIcon" : ""}`}>
  48. </div>
  49. );
  50. });
RAW Paste Data