【问题标题】:How to get the input(StyledComponent) value by ref如何通过 ref 获取输入(样式化组件)值
【发布时间】:2018-10-11 06:49:45
【问题描述】:

我正在尝试为样式化组件设置 ref。

组件已使用 const Input = styled.input 创建。但我无法通过参考获得输入值。

我的代码:

const _Input = styled.input`
  background-image: linear-gradient(#20aee3, #20aee3), linear-gradient(#bfbfbf, #bfbfbf);
  border: 0 none;
  border-radius: 0;
  box-shadow: none;
  float: none;
  background-color: transparent;
  background-position: center bottom, center calc(100% - 1px);
  background-repeat: no-repeat;
  background-size: 0 2px, 100% 1px;
  padding: 0;
  transition: background 0s ease-out 0s;
  color: #bfbfbf;
  min-height: 35px;
  display: initial;
  width: 100%;
  outline: none;
  font-size: 15px;
  &:focus {
      background-size: 100% 2px, 100% 1px;
      outline: 0 none;
      transition-duration: 0.3s;
      color: #525252;
    }
`;

...
<_Input type='text' ref="name" placeholder="name .."/>

【问题讨论】:

    标签: javascript reactjs input ref


    【解决方案1】:

    你需要使用

    innerRef="名称"

    对于样式化的组件 ref 将不起作用,您必须使用 innerRef。

    【讨论】:

    • 我收到一个错误:TypeError:无法读取未定义的属性“焦点”。当我使用 componentDidMount() { this.input.focus() }
    • <_input type="text" id="abc" innerref="{(comp)"> { this.input = comp }} placeholder="name"/>
    • 使用 <_input type="text" id="abc" innerref="{(comp)"> { this.input = comp; }} placeholder="name"/> 你忘了用分号。
    • 我仍然收到'未定义'
    • 我修复了未定义的错误。但是如何获取值表单输入
    【解决方案2】:

    好的,我想我明白了。 您无法从样式化组件中获取 ref。您需要将一些参数传递给它,然后将其作为引用传递给您正在使用的组件。 您可以查看此链接,例如: https://github.com/styled-components/styled-components/issues/1151

    【讨论】:

    • 但我无法在输入中获得价值
    猜你喜欢
    • 2021-01-09
    • 2020-07-26
    • 2020-09-07
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多