React js中单击element1时如何对element2进行单击?

问题描述 投票:1回答:2

我有两个独立的元素(不是父母-孩子)。

是否可以完成在单击StyledSearchInput时实际单击StyledDropDownInputAsync的行为。

        <StyledSearchInput/>
        <StyledDropdownInputAsync searchIcon
          className="options"
          placeholder="Search"
          loadOptions={loadOptions}
          onChange={this.handleSelection}
          cache={{}}
          filterOptions={(options) => (options)}>
        </StyledDropdownInputAsync>
javascript reactjs
2个回答
0
投票

您可以使用ref实现此类操作,

根据文档,Refs provide a way to access DOM nodes or React elements created in the render method.

您可以使用this链接阅读更多有关裁判的信息。

有关实现此类功能的信息,请参考this代码沙箱


0
投票

将它们包装在父组件中,定义点击状态,将点击状态传递给StyledDropdownInputAsync,将点击动作传递给StyledSearchInput

const ParentComp = () => {
  const [isClicked, setClick] = useState(false);
  return (
    <>
      <StyledSearchInput onClick={() => setClick(true)}/>
      <StyledDropdownInputAsync isClicked={isClicked} {...otherProps}>
      </StyledDropdownInputAsync>
    </>
  );
};

此在ReactJS中称为Lifting State Up

© www.soinside.com 2019 - 2024. All rights reserved.