styled-components Refs

2020-07-24 16:06 更新

Refs

通过传递ref prop给 styled component 将获得:

  • 底层 DOM 节点 (如果 styled 的对象是基本元素如 div)
  • React 组件实例 (如果 styled 的对象是 React Component)
const Input = styled.input`
  padding: 0.5em;
  margin: 0.5em;
  color: palevioletred;
  background: papayawhip;
  border: none;
  border-radius: 3px;
`;

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  render() {
    return (
      <Input
        ref={this.inputRef}
        placeholder="Hover to focus!"
        onMouseEnter={() => {
          this.inputRef.current.focus()
        }}
      />
    );
  }
}

render(
  <Form />
);
注意v3 或更低的版本请使用 innerRef prop instead.


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号