如何处理循环内的ref?
以下是我的父级组件,但是如何选择关注哪个输入呢?在这种情况下是否必须创建动态引用?
class TestRef extends React.Component { ref = React.createRef();
state = {
data: [
{
name: "abc"
},
{ name: "def" }
]
};
focusInput = () => this.ref.current.focus();
render() {
return (
<div>
{this.state.data.map(o => {
return <Hello placeholder={o.name} ref={this.ref} />;
})}
<button onClick={this.focusInput}>focus input 1</button>
<button onClick={this.focusInput}>focus input 2</button>
</div>
);
}
}
回答:
您可以使用回调引用来生成并将每个输入的动态引用存储在数组中。现在,您可以使用ref的索引来引用它们:
const Hello = React.forwardRef((props, ref) => <input ref={ref} />);class Button extends React.Component {
onClick = () => this.props.onClick(this.props.id);
render() {
return (
<button onClick={this.onClick}>{this.props.children}</button>
);
}
}
class TestRef extends React.Component {
state = {
data: [
{
name: "abc"
},
{ name: "def" }
]
};
inputRefs = [];
setRef = (ref) => {
this.inputRefs.push(ref);
};
focusInput = (id) => this.inputRefs[id].focus();
render() {
return (
<div>
{this.state.data.map(({ name }) => (
<Hello
placeholder={name}
ref={this.setRef}
key={name} />
))}
<Button onClick={this.focusInput} id={0}>focus input 1</Button>
<Button onClick={this.focusInput} id={1}>focus input 2</Button>
</div>
);
}
}
ReactDOM.render(<TestRef />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
以上是 如何处理循环内的ref? 的全部内容, 来源链接: utcz.com/qa/413228.html