react-ref

React Refs with TypeScript: Cannot read property 'current' of undefined

佐手、 提交于 2020-07-18 22:17:46
问题 I'm building a React application using TypeScript. I want to create button, that scrolls to a header of a child component on my main page. I've created a ref in the child component, following this stack overflow answer and (tried to) use forward refs to access it on my parent component. export class Parent extends Component { private testTitleRef!: RefObject<HTMLHeadingElement>; scrollToTestTitleRef = () => { if (this.testTitleRef.current !== null) { window.scrollTo({ behavior: "smooth", top:

Ref null inside Popover

眉间皱痕 提交于 2020-07-10 08:49:25
问题 I am trying to autofocus an input element on opening of a popover. Here is the sandbox for it: https://codesandbox.io/s/green-bash-x6bj4?file=/src/App.js Issue here is that the current property is always null on ref. Is this a case where forwardRef might help? I am not much aware of it so posting it. Any help is much appreciated. 回答1: No need to use a ref for that, just add autoFocus to your input: <input autoFocus placeholder="search" /> 回答2: Since you control the open via state, which is

Destructuring nested objects: How to get parent and it's children values?

白昼怎懂夜的黑 提交于 2019-12-17 16:47:12
问题 In the below function, I get the textarea object with the property current . Here, nested destructuring works with Start and End variables. But current variable doesn't work. function someFunction({ current: { selectionStart: Start, selectionEnd: End } }, AppStateSetter) { // do something with current, Start, and End } 回答1: The first destructuring creates only Start and End variables. If you want to create current as a variable, then you need to declare it again. function ({ current: {

Destructuring nested objects: How to get parent and it's children values?

半腔热情 提交于 2019-11-28 01:12:44
In the below function, I get the textarea object with the property current . Here, nested destructuring works with Start and End variables. But current variable doesn't work. function someFunction({ current: { selectionStart: Start, selectionEnd: End } }, AppStateSetter) { // do something with current, Start, and End } The first destructuring creates only Start and End variables. If you want to create current as a variable, then you need to declare it again. function ({ current: { selectionStart: Start, selectionEnd: End }, current }, AppStateSetter) { // do something with current , Start ,