React input focus event to display other component

自作多情 提交于 2021-02-19 03:07:23

问题


I was read some tutorial about this. They told me should using ref to do that. But It's very general.

Here is my problem: Basically in Header component include NavBar, SearchBar and ResultSearch component.

const Header = () => {
return (
    <header className="ss_header">
        <Navbar />
        <SearchBar />
        <ResultSearch />
    </header>
);
};

And In SearchBar component. Whenever I focused on input text. It emit an event and display ResultSearch component by any way (changing style, or ...).

class SearchBar extends Component{
render() {

    return (
        <div className="search_bar">
            <section className="search">
                <div className="sub_media container">
                    <form method="GET" action="" id="search_form">
                        <Icon icon="search" />
                        <span className="autocomplete">

                        <input
                            className="search_input"
                            autoCorrect="off"
                            autoComplete="off"
                            name="query"
                            type="text"
                            placeholder="Search for a movie, tv show, person..." />
                    </span>
                    </form>
                </div>
            </section>
        </div>
    );
}
}

Style in ResultSearch component. I was set display: none.

.results_search { display: none; }

I think ResultSearch will receive an event from SearchBar and set back display: block for ResultSearch component. Is possible?

How can I handle that? My Code here: https://codesandbox.io/s/3xv8xnx3z5


回答1:


only you should convert Header component like following:

class Header extends Component {
  state = {
    focus: false
  };

  handleInputFocus = () => {
    this.setState({ focus: true });
  };

  handleInputBlur = () => {
    this.setState({ focus: false });
  };

  render() {
    return (
      <header className="ss_header">
        <SearchBar
          onFocus={this.handleInputFocus}
          onBlur={this.handleInputBlur}
        />
        {this.state.focus ? <ResultSearch /> : null}
      </header>
    );
  }
}

and also in SearchBar component add following attributes to your input:

onFocus={this.props.onFocus}
onBlur={this.props.onBlur}

also, you should remove your CSS about result box.

And, you can see the updated code on the following sandbox:

https://codesandbox.io/s/mmj46xkpo9




回答2:


Still not sure what you're trying to achieve.

This is the way you can handle visibility of result of the search. Let me know if this isn't what you're looking for.

https://codesandbox.io/s/7jvz31xr66



来源:https://stackoverflow.com/questions/50979593/react-input-focus-event-to-display-other-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!