问题
I've started using Flow type on top of a project created with create-react-app tool. I struggle to make a simple scenario work where a class property is filled with element reference in render method but throws 2 errors. What am I doing wrong? All the checks should prevent those warnings.
class MyComponent extends React.Component<*> {
input: ?HTMLInputElement;
componentDidUpdate = () => {
if (this.input) {
this.input.focus();
if (this.input.value) {
const valueLength = this.input.value.length;
this.input.setSelectionRange(valueLength, valueLength);
}
}
};
render() {
return <input ref={ref => (this.input = ref)} />;
}
}
Error ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ src/todo/index.js:38:28
Property value is missing in null or undefined [1].
[1] 33│ input: ?HTMLInputElement;
34│
35│ componentDidUpdate = () => {
36│ if (this.input) {
37│ this.input.focus();
38│ if (this.input.value) {
39│ const valueLength = this.input.value.length;
40│ this.input.setSelectionRange(valueLength, valueLength);
41│ }
Error ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ src/todo/index.js:40:28
Cannot call this.input.setSelectionRange because property setSelectionRange is missing in null or undefined [1].
[1] 33│ input: ?HTMLInputElement;
34│
35│ componentDidUpdate = () => {
36│ if (this.input) {
37│ this.input.focus();
38│ if (this.input.value) {
39│ const valueLength = this.input.value.length;
40│ this.input.setSelectionRange(valueLength, valueLength);
41│ }
42│ }
43│ };
回答1:
Since you're calling methods, flow assumes that things could change at anytime. You need to keep a reference to the input and then you're all good. Something like below:
class MyComponent extends React.Component<*> {
input: ?HTMLInputElement;
componentDidUpdate = () => {
const { input } = this
if (input) {
input.focus();
if (input.value) {
const valueLength = input.value.length;
input.setSelectionRange(valueLength, valueLength);
}
}
};
render() {
return <input ref={ref => (this.input = ref)} />;
}
}
来源:https://stackoverflow.com/questions/49248680/flow-type-complains-about-class-property-assigned-via-react-ref