如何在 styled-component React 中获取 refs.value?

How get refs.value in styled-component React?

我想获取输入的引用值,没有样式组件:

<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)...}

如何在 styled-component 中获取 ref.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);....}

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

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

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

console.log(this.input.value)

您可以在不使用 ref

的情况下从 Event 获取值
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;

希望对您有所帮助!

从 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)`
`;