首页 > 解决方案 > 如何在样式化组件 React 中获取 refs.value?

问题描述

我想获得输入的参考值,没有样式组件:

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

标签: reactjsrefstyled-components

解决方案


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

console.log(this.input.value)

您可以在Event不使用的情况下从ref

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

有关React 表单的更多详细信息。

演示组件:

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;

希望能帮助到你!


推荐阅读