React ref binding results in: TypeError: Cannot read property 'focus' of null
React ref binding results in: TypeError: Cannot read property 'focus' of null
我可以复制 React 文档中的示例来创建一个 ref,然后将其定位到 Code Sandbox,但由于某些原因我无法在本地项目中复制它。我正在使用最新版本的 React 16.6.3。
TypeError: Cannot read property 'focus' of null
SelectDonation.save_donation_amount
src/components/SelectDonation.js:19
16 | save_donation_amount () {
17 |
18 | // testing refs
> 19 | this.customDonationInput.current.focus();
| ^ 20 |
21 | // prevent pageload
22 | // grab the custom amount
这是我的组件:
import React from "react";
import {Button, Modal, Form, Input, Radio} from 'semantic-ui-react';
import store from "../reducer";
export default class SelectDonation extends React.Component {
constructor(props) {
super(props);
this.customDonationInput = React.createRef();
this.save_donation_amount = this.save_donation_amount.bind(this);
}
save_donation_amount () {
this.customDonationInput.current.focus();
};
render() {
return (
<Form>
<Form.Input
type='number'
placeholder='Custom Amount'
name='donation_amount'
id='custom_amount'
ref={this.customDonationInput}
// value={store.donation_amount}
defaultValue={store.donation_amount}
/>
<Button
primary
onClick={
this.save_donation_amount
}>Next Step
</Button>
</Form>
)
}
}
从错误来看,.current 属性 似乎不存在。这可能是什么原因?
错误是因为Semantic UI React 的<Form.Input>
是函数式组件,因此无法接收refs。将元素更改为常规 <input>
解决了问题
我可以复制 React 文档中的示例来创建一个 ref,然后将其定位到 Code Sandbox,但由于某些原因我无法在本地项目中复制它。我正在使用最新版本的 React 16.6.3。
TypeError: Cannot read property 'focus' of null
SelectDonation.save_donation_amount
src/components/SelectDonation.js:19
16 | save_donation_amount () {
17 |
18 | // testing refs
> 19 | this.customDonationInput.current.focus();
| ^ 20 |
21 | // prevent pageload
22 | // grab the custom amount
这是我的组件:
import React from "react";
import {Button, Modal, Form, Input, Radio} from 'semantic-ui-react';
import store from "../reducer";
export default class SelectDonation extends React.Component {
constructor(props) {
super(props);
this.customDonationInput = React.createRef();
this.save_donation_amount = this.save_donation_amount.bind(this);
}
save_donation_amount () {
this.customDonationInput.current.focus();
};
render() {
return (
<Form>
<Form.Input
type='number'
placeholder='Custom Amount'
name='donation_amount'
id='custom_amount'
ref={this.customDonationInput}
// value={store.donation_amount}
defaultValue={store.donation_amount}
/>
<Button
primary
onClick={
this.save_donation_amount
}>Next Step
</Button>
</Form>
)
}
}
从错误来看,.current 属性 似乎不存在。这可能是什么原因?
错误是因为Semantic UI React 的<Form.Input>
是函数式组件,因此无法接收refs。将元素更改为常规 <input>
解决了问题