我有一个应用程序,我需要在其中管理对输入的关注,为此我使用 Reactref
.
我有两个输入想要移动到一个单独的组件中。现在它们看起来如下:
<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"));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)