我有一个应用程序,我需要在其中管理对输入的关注,为此我使用 React
ref
。
我有两个输入想要移动到一个单独的组件中。现在它们看起来如下:
<input
onChange={this.handleChangeOne}
ref={refOne => (this.refOne = refOne as HTMLInputElement)}
type="text"
/>
<input
onChange={this.handleChangeTwo}
ref={refTwo => (this.refTwo = refTwo as HTMLInputElement)}
type="text"
/>
我很难让它们在单独的组件中工作,同时涉及传递 ref 属性。我尝试过这样的事情:
<InputBlock
handleChangeOne={() => this.handleChangeOne}
handleChangeTwo={() => this.handleChangeTwo}
refOne=(refOne => (this.refOne = refOne as HTMLInputElement)}
refTwo={refTwo => (this.refTwo = refTwo as HTMLInputElement)}
/>
以及组件本身
class InputBlock extends React.Component<IProps> {
public render() {
return (
<React.Fragment>
<input
ref={refOne}
onChange={handleChangeOne}
type="text"
/>
<input
ref={refTwo}
onChange={handleChangeTwo}
type="text"
/>
</React.Fragment>
);
}
}
export default InputBlock;
为了举例,我希望
handleChangeOne
专注于输入二,而 handleChangeTwo
专注于输入一
我不知道你出了什么问题,但以下对我有用:
import * as React from "react";
import * as ReactDOM from "react-dom";
class OuterComponent extends React.Component<{}, {}> {
refOne: null | HTMLInputElement = null;
refTwo: null | HTMLInputElement = null;
render() {
return <InputBlock
handleChangeOne={this.handleChangeOne}
handleChangeTwo={this.handleChangeTwo}
refOne={refOne => (this.refOne = refOne)}
refTwo={refTwo => (this.refTwo = refTwo)}
/>;
}
handleChangeOne = () => {
console.log("handleChangeOne", this.refOne, this.refTwo);
}
handleChangeTwo = () => {
console.log("handleChangeTwo", this.refOne, this.refTwo);
}
}
interface IProps {
refOne: React.Ref<HTMLInputElement>;
refTwo: React.Ref<HTMLInputElement>;
handleChangeOne: React.ChangeEventHandler<HTMLInputElement>;
handleChangeTwo: React.ChangeEventHandler<HTMLInputElement>;
}
class InputBlock extends React.Component<IProps> {
public render() {
return (
<React.Fragment>
<input
ref={this.props.refOne}
onChange={this.props.handleChangeOne}
type="text"
/>
<input
ref={this.props.refTwo}
onChange={this.props.handleChangeTwo}
type="text"
/>
</React.Fragment>
);
}
}
ReactDOM.render(<OuterComponent/>, document.getElementById("root"));
对于功能组件:
import React,{useRef} from 'react';
const ParentComp = () => {
const parentDivRef = useRef<HTMLButtonElement>(null);
return(
<ChildButtonComp ref={parentDivRef}>Click Me</ChildButtonComp>
)
}
import React, { Ref, forwardRef,ReactNode } from "react";
const ChildButtonComp = forwardRef(
(props: { children: ReactNode }, ref: Ref<HTMLButtonElement>) => {
return <button ref={ref}>{props.children}</button>;
}
);