我有一个名为Home
的组件,其中包含LeftNav
,BookSearch
和HomeCart
组件。 BookSearch
组件具有输入字段,HomeCart
组件具有按钮。 点击HomeCart
组件中的按钮后,我需要将焦点集中在BookSearch
组件中的输入字段。
我做了一些研究,我只能只关注同一组件中的一个元素。如何使用React Ref实现所需的行为?
Home.jsx
class Home extends React.Component {
render() {
return (
<React.Fragment>
<div className="row no-gutters app">
<div className="col-sm-12 col-md-12 col-lg-2">
<LeftNav />
</div>
<div className="col-sm-12 col-md-12 col-lg-7 books-panel">
<BookSearch test={this.test}/>
</div>
<div className="col-sm-12 col-md-12 col-lg-3 cart-panel">
<HomeCart onClick={thi} />
</div>
</div>
</React.Fragment>
);
}
}
BookSearch.jsx
class BookSearch extends React.Component {
render() {
return (
<React.Fragment>
<button onClick={this.test}>Focus</button>
<div className="row text-center">
<div className="col-12">
<form onSubmit={this.handleSubmit}>
<h2 className="mt-5">Start searching your favorite books</h2>
<label htmlFor="search-query" className="sr-only">
Search by book name
</label>
<input
name="search-query"
onChange={this.handleChange}
type="search"
className="book-search"
value={this.state.query}
placeholder="Start searching...."
/>
<button type="submit" className="btn btn-primary btn-lg">
Search
</button>
</form>
</div>
</div>
</React.Fragment>
);
}
}
HomeCart.jsx
class HomeCart extends React.Component {
focusSearchBookInput(){
this.props.focusSearchBookInput()
}
render() {
const { cart_items } = this.props;
const cartTable = ();
const noCartItems = (
<React.Fragment>
<p>No items currently available in your cart. </p>
<button onClick={this.focusSearchBookInput} className="btn btn-success mt-5">
<ion-icon name="search" /> Start Searching
</button>
</React.Fragment>
);
return (
<React.Fragment>
<div className="row text-center">
<div className="col-12">
<h2 className="mt-5 mb-5">Books in your cart</h2>
{cart_items.length > 0 ? cartTable : noCartItems}
</div>
</div>
</React.Fragment>
);
}
}
答案 0 :(得分:0)
一个解决方案可能是...
创建引用和单击处理程序,以将焦点放在 Home.jsx
中的引用上class Home extends React.Component {
inputRef = React.createRef();
focusHandler = () => {
this.inputRef.current.focus();
}
render() {
return (
<React.Fragment>
<div className="row no-gutters app">
<div className="col-sm-12 col-md-12 col-lg-2">
<LeftNav />
</div>
<div className="col-sm-12 col-md-12 col-lg-7 books-panel">
<BookSearch inputRef={this.inputRef} />
</div>
<div className="col-sm-12 col-md-12 col-lg-3 cart-panel">
<HomeCart focusHandler={this.focusHandler} />
</div>
</div>
</React.Fragment>
);
}
}
将ref={this.props.inputRef}
添加到 BookSearch.jsx
将onClick={this.props.focusHandler}
添加到 HomeCart.jsx