Created
April 8, 2020 09:26
-
-
Save dandelionadia/22801d4bc78612afeee80046a826f20c to your computer and use it in GitHub Desktop.
Using Refs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person extends Component { | |
constructor(props) { | |
super(props); | |
this.inputElementRef = React.creatRef(); | |
} | |
componentDidMount() { | |
this.inputElementRef.current.focus(); | |
} | |
render() { | |
return ( | |
<input ref={this.inputElementRef} type="text"/> | |
) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const Cockpit: React.FC<CockpitProps> = React.memo(props => { | |
const toggleBtnRef = useRef<HTMLButtonElement>(null); | |
useEffect(() => { | |
const { current } = toggleBtnRef; | |
if (!current) { | |
return; | |
} | |
current.click(); | |
}, []); | |
return ( | |
<> | |
<h1>React App</h1> | |
<button ref={toggleBtnRef} onClick={props.onClick}> | |
Switch Name | |
</button> | |
</> | |
); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const Cockpit: React.FC<CockpitProps> = React.memo(props => { | |
const toggleBtnRef = useRef<HTMLButtonElement>(null); | |
useEffect(() => { | |
toggleBtnRef.current?.click() | |
}, []); | |
return ( | |
<> | |
<button ref={toggleBtnRef} onClick={props.onClick}> | |
Switch Name | |
</button> | |
</> | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment