Я пытаюсь программно настроить фокус на вводе, но по какой-то причине мой код не работает. Надеюсь, кто-нибудь сможет сказать мне, что я делаю не так.
class ParentComponent extends React.Component {
inputRef = React.createRef<HTMLInputElement>()
focusInput = ()=> {
const node = this.inputRef.current
if(node) {
console.log(node) // <input type="number" value />
node.focus() // However focus is not set on the input
}
}
getInputRef = ()=> {
return this.inputRef
}
render(){
return <ChildComponent getInputRef={this.getInputRef} focusInput={this.focusInput} />
}
}
const ChildComponent: React.FC<any> = ({getInputRef, focusInput})=> (
<React.Fragment>
<input
type="number"
ref={()=>getInputRef()}
/>
<button onClick={()=>focusInput()}>Set Focus</button>
</React.Fragment>
)
1
lomse
19 Окт 2019 в 00:14
1 ответ
Лучший ответ
Вам необходимо использовать React.forwardRef
для передачи ref
, определенного в родительском компоненте, в функциональный дочерний компонент. Попробуйте что-то вроде этого:
Родитель
class ParentComponent extends React.Component {
inputRef = React.createRef();
focusInput = () => {
const node = this.inputRef.current;
if (node) {
node.focus();
}
};
render() {
return <ChildComponent ref={this.inputRef} focusInput={this.focusInput} />;
}
}
Ребенок
const ChildComponent = React.forwardRef((props, ref) => {
return (
<div>
<input ref={ref} />
<button onClick={() => props.focusInput()}>Set Focus</button>
</div>
);
});
Вот песочница для вашей справки: https://codesandbox.io/s/reactforwardref-o1jtt
2
Cool Guy
18 Окт 2019 в 21:29
Похожие вопросы
Новые вопросы
reactjs
React - это библиотека JavaScript для создания пользовательских интерфейсов. Он использует декларативную компонентную парадигму и стремится быть одновременно эффективным и гибким.