简体   繁体   English

reactjs中如何访问嵌套对象

[英]How to access the nested object in react js

I have handle click and I want to access the className of the div element, how can I do that我已经处理了点击,我想访问 div 元素的 className,我该怎么做

  1. this is the element i want to get the div className这是我想要获取 div className 的元素

     <div className="milad"> <IconButton style={{outline:'none', color: 'white', float:'right', marginRight:'20px', marginTop: "5px"}} className = "iconButton" >menu <MenuIcon/> </IconButton> </div>
  2. this is my这是我的

    checkHandleClick = (event) => { console.log(event); } ----------------------------------------------------------------- <ClickAwayListener onClickAway={((e) => this.checkHandleClick(e))}> -----some code------ </ClickAwayListener>

I want to access this Console.log我想访问这个Console.log

You could do using event.target.className你可以使用event.target.className

checkHandleClick = (event) => {
    console.log(event.target.className);
}
-----------------------------------------------------------------
<ClickAwayListener onClickAway={((e) => this.checkHandleClick(e))}>
-----some code------
</ClickAwayListener>

You should use ref for it.你应该使用 ref 。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

Or if you're using hooks或者如果你使用钩子

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM