如何在样式化组件React中获取refs.value?

时间:2018-08-27 19:03:26

标签: reactjs ref styled-components

我想获取输入的ref值,而没有样式化的组件:

<form  role='form' method='POST' onSubmit= {::this.onSubmit}>               
<input id='name' type='text' ref='name' name='name'  required/>
<button> Register</button></form>


 onSubmit(e){
    e.preventDefault();
    console.log(this.refs.name.value)...}

如何在样式组件中获取参考值?

  <form  role='form' method='POST' onSubmit= {::this.onSubmit}>               
<StyledInput innerRef={name => { this.input = name }} id='name' type='text' name='name' />
<button> Register</button></form>  

 onSubmit(e){
e.preventDefault();
console.log(this.input);....}

3 个答案:

答案 0 :(得分:2)

添加innerRef={name => { this.input = name }}可使输入节点通过this.input

可用
console.log(this.input.value)

您可以从Event获取值,而无需使用ref

onSubmit(e) {
    console.log(e.target.value)
}

有关React forms.

的更多详细信息

演示组件:

import React from "react";
import styled from "styled-components";

const InputStyled = styled.input`
  background: lightgreen;
`;

class Test extends React.Component {
  onChange = e => {
    console.log(this.input.value);
    console.log(e.target.value);
  };
  render = () => {
    return (
      <InputStyled
        onChange={this.onChange}
        innerRef={input => (this.input = input)}
      />
    );
  };
}

export default Test;

希望有帮助!

答案 1 :(得分:1)

不确定StyledInput如何与ref一起使用,但是您可以使用ref对象的.current键访问ref节点。

https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs

答案 2 :(得分:0)

自React 16.8.0起。带有钩子,您可以使用useRef-

以以下方式访问引用
import React, { useRef } from 'react';

...

const inputRef = useRef(null);

...

<StyledInput ref={inputRef} />

<Button onClick={()=>{inputRef.current.focus()}}>Focus on input</Button>


...

const StyledInput = styled(input)`
`;

const Button = styled(button)`
`;