javascript - Reactjs 从自定义组件中检索值
问题描述
ReactJS 的新手,我正在尝试编写自定义组件;但是,我被困在如何检索父组件中的值。
假设我有一个自定义组件输入组件:
import React,{Component} from "react";
class TextField extends Component{
render(){
const inpStyle = {width: this.props.width || "100%",height: this.props.height || ""}
const inpClass = (this.props.error !=="" ? "error" : "")
const autofocus= this.props.autofocus || false;
const disabled = typeof this.props.active==="undefined"|| this.props.active===false;
return(
<div>
<label htmlFor={this.props.id}>{this.props.label} </label>
<input
className={inpClass}
style={inpStyle}
id={this.props.id}
name={this.props.id}
value={this.props.value}
type={this.props.type || "text"}
disabled={!disabled}
autoFocus={autofocus}
placeholder={this.props.placehoder}
onChange={this.props.handleChange}
onFocus={this.props.handleFocus}
onBlur={this.props.handleBlur}
/>
<div className="errortxt">{this.props.error}</div>
</div>
)
}
}
export default TextField
refs
有没有一种方法可以在不使用或我求助的情况下检索组件值(ReactJS 方式)document.getElementById(...).value
假设 state 包含以下值,并且定义的方法确实在 Parent 组件中定义:
render = () => {
return(
<div>
<Panel width="400px" showtitle={false} shadow={true} title="Please Log In" hideclose={true}>
<TextField
id="emailaddress"
label="Email Address:"
value={this.state.fields.emailaddress.value}
error={this.state.fields.emailaddress.error}
autoFocus={this.state.fields.emailaddress.value !== "" ? false : true}
handleChange={this.handleChange}
handleFocus={this.handleFocus}
/>
解决方案
React 是关于在组件树中向下流动的数据。所以state
应该归Parent
. CustomInput
接收 avalue
以及如何从它的父级更改它。像这样的东西
const Parent = () =>{
const[value, setValue] = useState('')
return <CustomInput value={value} setValue={setValue} />
}
const CustomInput = ({ value, setValue }) =>(
<input className='fancy-input' value={value} onChange={e => setValue(e.target.value) />}
)
这样,您可以在Parent
不破坏正常流程的情况下“访问”输入的值,并且我将访问放在引号之间,因为您实际上并没有访问value
,它property
已经被Parent
推荐阅读
- r - 如何让 R 预测用户输入
- python-3.x - 天空场数据以获取给定日期范围内的远地点和近地点
- elasticsearch - 使用 logstash 将数据集导入到 ElasticSearch 很慢
- php - Docker 容器上的 PHP XDebug 在 VS Code 中不起作用(Laravel 和 docker-compose)
- javascript - 是否有任何选项可以通过循环将 div id 降低一个?
- python - 根据元素名称在python中对长列表的元素进行分组
- mysql - 存储过程语法错误中的临时表
- java - Android:我的创建表语句有什么问题?
- c++ - 流利的编程内存分配问题 C++
- android - 接收广播 Intent 时出错 { act=com.google.android.gms.appinvite.intent.action.INVITE_SENT