Как получить refs.value в стиле React компонента? - PullRequest
0 голосов
/ 27 августа 2018

Я хочу получить значение 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)...}

Как получить ref.value в styled-component?

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

Ответы [ 2 ]

0 голосов
/ 27 августа 2018

Добавление innerRef={name => { this.input = name }} делает входной узел доступным через this.input

console.log(this.input.value)

Вы можете получить значение из Event без использования ref

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

Подробнее о Реактивные формы.

Демо-компонент:

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;

Надеюсь, это поможет!

0 голосов
/ 27 августа 2018

Не уверен, как StyledInput работает с refs, но вы можете получить доступ к узлу ref с помощью ключа .current объекта ref.

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

...