reactjs - 如何在样式化组件 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);....}
解决方案
添加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;
希望能帮助到你!
推荐阅读
- java - 处理 Spring Webflux MultipartFile.transferTo 中的错误
- scala - 在 Spark 中使用 map() 和 filter() 而不是 spark.sql
- python - 更改日期时间的 x 轴,例如在 python 中使用 matplotlib 修剪图形
- r - qwraps2::summary_table() 交叉引用汇总表
- alloy - 合金中的 sig 文字
- python - 我已经启动了 8 个线程,但 CPU 使用率几乎与单线程相同
- php - 使用标签 HTML 将数据提取到活动协作任务中 - PHP
- sql - 如何将 SQL 转换为每个 ID 一行的 XML 模式(用于 XML RAW)
- sql - 具有多个 NotLike 数据库名称过滤器的 Powershell 和 SQL
- python - 使用 Python 对 Sharepoint REST API 进行身份验证时出现未经授权的错误